Android开发-基础网络组件(1)使用HttpURLConnection登陆-注意打开网络需要在线程中执行-主线程不支持

转载请注明出处:http://blog.****.net/iwanghang/article/details/70685334
觉得博文有用,请点赞,请评论,请关注,谢谢!~


老规矩,先上GIF动态图,看个效果,如果符合你的项目或者确定你要了解的内容,再往下看吧:

Android开发-基础网络组件(1)使用HttpURLConnection登陆-注意打开网络需要在线程中执行-主线程不支持


接口使用php本地服务器,简单说就是使用phpStudy开启本地服务器,不会的同学请看我写的关于php的博文:


这个是最基础的方法来实现登陆,虽然方法比较low,但是了解原理来说,最好不过。只是,不建议在实际项目中使用,因为比较代码量比较大。


以下是php和Android的代码:


php:

login.php:

[php] view plain copy
  1. <?php  
  2. $action = isset($_POST['action']) ? $_POST['action'] : '';  
  3. $username = isset($_POST['username']) ? $_POST['username'] : '';  
  4. $password = isset($_POST['password']) ? $_POST['password'] : '';  
  5.   
  6. if($action=='login') {  
  7.     login($username$password);  
  8. else {  
  9.     $result = array("login"=>"error");  
  10.     $json = json_encode($result);  
  11.     echo $json;  
  12. }  
  13.   
  14. /*用户登录*/  
  15. function login($username$password) {  
  16.         $result = null;  
  17.         if($username=="iwanghang" && $password=="123") {  
  18.             $result = array("login"=>$username."---".$password."---success");  
  19.             $json = json_encode($result);  
  20.         }else{  
  21.             $result = array("login"=>"账户名或密码操作");  
  22.             $json = json_encode($result);  
  23.         }  
  24.     echo $json;  
  25. }  


Android:

activity_main.xml:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:orientation="vertical"  
  5.     android:id="@+id/activity_main"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  10.     android:paddingRight="@dimen/activity_horizontal_margin"  
  11.     android:paddingTop="@dimen/activity_vertical_margin"  
  12.     tools:context="com.iwanghang.httpurlconnectiondemo.MainActivity">  
  13.   
  14.     <TextView  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:gravity="center"  
  18.         android:text="Hello World!"  
  19.         android:id="@+id/textView_info" />  
  20.   
  21.     <LinearLayout  
  22.         android:layout_width="match_parent"  
  23.         android:layout_height="wrap_content">  
  24.   
  25.         <TextView  
  26.             android:textSize="15sp"  
  27.             android:text="账号"  
  28.             android:layout_width="wrap_content"  
  29.             android:layout_height="wrap_content"  
  30.             android:id="@+id/textView2" />  
  31.   
  32.         <EditText  
  33.             android:textSize="15sp"  
  34.             android:layout_width="match_parent"  
  35.             android:layout_height="wrap_content"  
  36.             android:inputType="textPersonName"  
  37.             android:hint="请输入用户名"  
  38.             android:ems="10"  
  39.             android:id="@+id/editText_userName" />  
  40.   
  41.     </LinearLayout>  
  42.   
  43.     <LinearLayout  
  44.         android:layout_width="match_parent"  
  45.         android:layout_height="wrap_content">  
  46.   
  47.         <TextView  
  48.             android:textSize="15sp"  
  49.             android:text="密码"  
  50.             android:layout_width="wrap_content"  
  51.             android:layout_height="wrap_content"  
  52.             android:id="@+id/textView3" />  
  53.   
  54.         <EditText  
  55.             android:textSize="15sp"  
  56.             android:layout_width="match_parent"  
  57.             android:layout_height="wrap_content"  
  58.             android:inputType="textPassword"  
  59.             android:hint="请输入密码"  
  60.             android:ems="10"  
  61.             android:id="@+id/editText_passWord"  
  62.             android:layout_weight="1" />  
  63.   
  64.     </LinearLayout>  
  65.   
  66.     <Button  
  67.         android:text="登陆"  
  68.         android:layout_width="match_parent"  
  69.         android:layout_height="wrap_content"  
  70.         android:onClick="loginClick"  
  71.         android:id="@+id/button_login" />  
  72. </LinearLayout>  


MainActivity.java:(未使用handler设置textView_info)

[java] view plain copy
  1. package com.iwanghang.httpurlconnectiondemo;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.text.TextUtils;  
  6. import android.view.View;  
  7. import android.widget.EditText;  
  8. import android.widget.TextView;  
  9.   
  10. import java.io.BufferedReader;  
  11. import java.io.DataOutputStream;  
  12. import java.io.IOException;  
  13. import java.io.InputStreamReader;  
  14. import java.net.HttpURLConnection;  
  15. import java.net.MalformedURLException;  
  16. import java.net.URL;  
  17. import java.net.URLEncoder;  
  18.   
  19. public class MainActivity extends AppCompatActivity {  
  20.   
  21.     private TextView textView_info;  
  22.     private EditText editText_userName;  
  23.     private EditText editText_passWord;  
  24.   
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.   
  30.         textView_info = (TextView) findViewById(R.id.textView_info);  
  31.         editText_userName = (EditText) findViewById(R.id.editText_userName);  
  32.         editText_passWord = (EditText) findViewById(R.id.editText_passWord);  
  33.   
  34.     }  
  35.   
  36.     public void loginClick(View view){  
  37.         final String userName = editText_userName.getText().toString();  
  38.         if (TextUtils.isEmpty(userName)){  
  39.             textView_info.setText("用户名不能为空");  
  40.             return;  
  41.         }  
  42.   
  43.         final String passWord = editText_passWord.getText().toString();  
  44.         if (TextUtils.isEmpty(passWord)){  
  45.             textView_info.setText("密码不能为空");  
  46.             return;  
  47.         }  
  48.   
  49.         // 启动登陆工作线程  
  50.         new Thread(new Runnable() {  
  51.             @Override  
  52.             public void run() {  
  53.                 // 接口地址  
  54.                 String path= "http://192.168.1.114/login.php";  
  55. //                String path= "http://192.168.1.40/login.php";  
  56.                 try {  
  57.                     URL url = new URL(path);  
  58.                     // 打开http链接  
  59.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  60.                     conn.setRequestMethod("POST");  
  61.                     conn.setDoInput(true);  
  62.                     conn.setDoOutput(true);  
  63.                     conn.setConnectTimeout(1000*30); // 连接超时时间  
  64.                     conn.setReadTimeout(1000*30); // 读取数据超时时间  
  65.                     conn.setUseCaches(false);  
  66.                     conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
  67.                     // 对服务器端读取或者写入数据(使用输入输出流)  
  68.                     // 获取连接的输出流  
  69.                     DataOutputStream dos = new DataOutputStream(conn.getOutputStream());  
  70.                     // action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商  
  71.                     // 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述  
  72.                     // 接口php同事怎么写你就怎么传  
  73.                     dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));  
  74.                     dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));  
  75.                     dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));  
  76.                     dos.flush();  
  77.                     dos.close();  
  78.                     // 从服务器获取相应数据  
  79.                     BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  80.                     String result = br.readLine();  
  81.                     System.out.println("result == " + result);  
  82.                     br.close();  
  83.                 } catch (MalformedURLException e) {  
  84.                     e.printStackTrace();  
  85.                 } catch (IOException e) {  
  86.                     e.printStackTrace();  
  87.                 }  
  88.             }  
  89.         }).start();  
  90.     }  
  91. }  

至此,可以AndroidStudio的控制台查看的服务器返回的结果,但是没有显示到UI上面,下一篇博文,我们把服务器的结果显示在UI上。

调试信息:

[html] view plain copy
  1. 04-25 03:12:44.886 5373-7416/com.iwanghang.httpurlconnectiondemo I/System.out: result == {"login":"iwanghang---123---success"}  
  2. 04-25 03:12:46.589 5373-7446/com.iwanghang.httpurlconnectiondemo I/System.out: result == {"login":"\u8d26\u6237\u540d\u6216\u5bc6\u7801\u64cd\u4f5c"}  

不要忘记访问网络的权限:

[html] view plain copy
  1. <uses-permission android:name="android.permission.INTERNET"/>  


----------

MainActivity.java:(使用handler设置textView_info)

[java] view plain copy
  1. package com.iwanghang.httpurlconnectiondemo;  
  2.   
  3. import android.os.Handler;  
  4. import android.os.Message;  
  5. import android.support.v7.app.AppCompatActivity;  
  6. import android.os.Bundle;  
  7. import android.text.TextUtils;  
  8. import android.view.View;  
  9. import android.widget.EditText;  
  10. import android.widget.TextView;  
  11.   
  12. import java.io.BufferedReader;  
  13. import java.io.DataOutputStream;  
  14. import java.io.IOException;  
  15. import java.io.InputStreamReader;  
  16. import java.lang.ref.WeakReference;  
  17. import java.net.HttpURLConnection;  
  18. import java.net.MalformedURLException;  
  19. import java.net.URL;  
  20. import java.net.URLEncoder;  
  21.   
  22. public class MainActivity extends AppCompatActivity {  
  23.   
  24.     private TextView textView_info;  
  25.     private EditText editText_userName;  
  26.     private EditText editText_passWord;  
  27.   
  28.     private final MyHandler myHandler = new MyHandler(this);  
  29.     private static final int LOAD_SUCESS = 0x1;  
  30.   
  31.     @Override  
  32.     protected void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.activity_main);  
  35.   
  36.         textView_info = (TextView) findViewById(R.id.textView_info);  
  37.         editText_userName = (EditText) findViewById(R.id.editText_userName);  
  38.         editText_passWord = (EditText) findViewById(R.id.editText_passWord);  
  39.   
  40.     }  
  41.   
  42.     public void loginClick(View view){  
  43.         final String userName = editText_userName.getText().toString();  
  44.         if (TextUtils.isEmpty(userName)){  
  45.             textView_info.setText("用户名不能为空");  
  46.             return;  
  47.         }  
  48.   
  49.         final String passWord = editText_passWord.getText().toString();  
  50.         if (TextUtils.isEmpty(passWord)){  
  51.             textView_info.setText("密码不能为空");  
  52.             return;  
  53.         }  
  54.   
  55.         // 启动登陆工作线程  
  56.         new Thread(new Runnable() {  
  57.             @Override  
  58.             public void run() {  
  59.                 // 接口地址  
  60.                 String path= "http://192.168.1.114/login.php";  
  61. //                String path= "http://192.168.1.40/login.php";  
  62.                 try {  
  63.                     URL url = new URL(path);  
  64.                     // 打开http链接  
  65.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  66.                     conn.setRequestMethod("POST");  
  67.                     conn.setDoInput(true);  
  68.                     conn.setDoOutput(true);  
  69.                     conn.setConnectTimeout(1000*30); // 连接超时时间  
  70.                     conn.setReadTimeout(1000*30); // 读取数据超时时间  
  71.                     conn.setUseCaches(false);  
  72.                     conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
  73.                     // 对服务器端读取或者写入数据(使用输入输出流)  
  74.                     // 获取连接的输出流  
  75.                     DataOutputStream dos = new DataOutputStream(conn.getOutputStream());  
  76.                     // action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商  
  77.                     // 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述  
  78.                     // 接口php同事怎么写你就怎么传  
  79.                     dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));  
  80.                     dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));  
  81.                     dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));  
  82.                     dos.flush();  
  83.                     dos.close();  
  84.                     // 从服务器获取相应数据  
  85.                     BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  86.                     String result = br.readLine();  
  87.                     System.out.println("result == " + result);  
  88.                     br.close();  
  89.                     conn.disconnect();  
  90.                     // 通过handler把result传出去  
  91.                     Message msg = myHandler.obtainMessage(LOAD_SUCESS,result);  
  92.                     myHandler.sendMessage(msg);  
  93.                 } catch (MalformedURLException e) {  
  94.                     e.printStackTrace();  
  95.                 } catch (IOException e) {  
  96.                     e.printStackTrace();  
  97.                 }  
  98.             }  
  99.         }).start();  
  100.     }  
  101.   
  102.   
  103.     private static class MyHandler extends Handler {  
  104.         private final WeakReference<MainActivity> weakReference;   // 软引用  
  105.         public MyHandler(MainActivity mainActivity){  
  106.             weakReference = new WeakReference<MainActivity>(mainActivity);  
  107.         }  
  108.         @Override  
  109.         public void handleMessage(Message msg) {  
  110.             MainActivity mainActivity = weakReference.get();  
  111.             if (mainActivity!=null){  
  112.                 switch (msg.what){  
  113.                     case LOAD_SUCESS:  
  114.                         mainActivity.textView_info.setText((String)msg.obj); // 获取msg 设置UI显示  
  115.                         break;  
  116.                 }  
  117.             }  
  118.         }  
  119.     }  
  120. }  




转载请注明出处:http://blog.****.net/iwanghang/article/details/70685334



欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android,请与我联系
联系方式
Android开发-基础网络组件(1)使用HttpURLConnection登陆-注意打开网络需要在线程中执行-主线程不支持
微信:iwanghang
QQ:413711276
邮箱:[email protected]