热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

转载请注明出处:http:blog.csdn.netiwanghangarticledetails70685334觉得博文有用,请点赞,
转载请注明出处:
http://blog.csdn.net/iwanghang/article/details/70685334


觉得博文有用,请点赞,请评论,请关注,谢谢!~





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



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


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


以下是php和Android的代码:



php:


login.php:


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



Android:


activity_main.xml:


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






MainActivity.java&#xff1a;&#xff08;未使用handler设置textView_info&#xff09;


[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.     &#64;Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.   
  30.         textView_info &#61; (TextView) findViewById(R.id.textView_info);  
  31.         editText_userName &#61; (EditText) findViewById(R.id.editText_userName);  
  32.         editText_passWord &#61; (EditText) findViewById(R.id.editText_passWord);  
  33.   
  34.     }  
  35.   
  36.     public void loginClick(View view){  
  37.         final String userName &#61; editText_userName.getText().toString();  
  38.         if (TextUtils.isEmpty(userName)){  
  39.             textView_info.setText("用户名不能为空");  
  40.             return;  
  41.         }  
  42.   
  43.         final String passWord &#61; editText_passWord.getText().toString();  
  44.         if (TextUtils.isEmpty(passWord)){  
  45.             textView_info.setText("密码不能为空");  
  46.             return;  
  47.         }  
  48.   
  49.         // 启动登陆工作线程  
  50.         new Thread(new Runnable() {  
  51.             &#64;Override  
  52.             public void run() {  
  53.                 // 接口地址  
  54.                 String path&#61; "http://192.168.1.114/login.php";  
  55. //                String path&#61; "http://192.168.1.40/login.php";  
  56.                 try {  
  57.                     URL url &#61; new URL(path);  
  58.                     // 打开http链接  
  59.                     HttpURLConnection conn &#61; (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.                     // 对服务器端读取或者写入数据&#xff08;使用输入输出流&#xff09;  
  68.                     // 获取连接的输出流  
  69.                     DataOutputStream dos &#61; new DataOutputStream(conn.getOutputStream());  
  70.                     // action&#61;login 表示登陆 也可以等于别的 主要看你的php同事如何协商  
  71.                     // 一般来说 action&#61;login 表示登陆 action&#61;update 表示修改密码 不多赘述  
  72.                     // 接口php同事怎么写你就怎么传  
  73.                     dos.writeBytes("action&#61;"&#43; URLEncoder.encode("login","UTF8"));  
  74.                     dos.writeBytes("&username&#61;"&#43; URLEncoder.encode(userName,"UTF8"));  
  75.                     dos.writeBytes("&password&#61;"&#43; URLEncoder.encode(passWord,"UTF8"));  
  76.                     dos.flush();  
  77.                     dos.close();  
  78.                     // 从服务器获取相应数据  
  79.                     BufferedReader br &#61; new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  80.                     String result &#61; br.readLine();  
  81.                     System.out.println("result &#61;&#61; " &#43; result);  
  82.                     br.close();  
  83.                 } catch (MalformedURLException e) {  
  84.                     e.printStackTrace();  
  85.                 } catch (IOException e) {  
  86.                     e.printStackTrace();  
  87.                 }  
  88.             }  
  89.         }).start();  
  90.     }  
  91. }  




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


调试信息&#xff1a;


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




不要忘记访问网络的权限&#xff1a;


[html] view plain copy
  1. <uses-permission android:name&#61;"android.permission.INTERNET"/>  





----------


MainActivity.java&#xff1a;&#xff08;使用handler设置textView_info&#xff09;


[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 &#61; new MyHandler(this);  
  29.     private static final int LOAD_SUCESS &#61; 0x1;  
  30.   
  31.     &#64;Override  
  32.     protected void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.activity_main);  
  35.   
  36.         textView_info &#61; (TextView) findViewById(R.id.textView_info);  
  37.         editText_userName &#61; (EditText) findViewById(R.id.editText_userName);  
  38.         editText_passWord &#61; (EditText) findViewById(R.id.editText_passWord);  
  39.   
  40.     }  
  41.   
  42.     public void loginClick(View view){  
  43.         final String userName &#61; editText_userName.getText().toString();  
  44.         if (TextUtils.isEmpty(userName)){  
  45.             textView_info.setText("用户名不能为空");  
  46.             return;  
  47.         }  
  48.   
  49.         final String passWord &#61; editText_passWord.getText().toString();  
  50.         if (TextUtils.isEmpty(passWord)){  
  51.             textView_info.setText("密码不能为空");  
  52.             return;  
  53.         }  
  54.   
  55.         // 启动登陆工作线程  
  56.         new Thread(new Runnable() {  
  57.             &#64;Override  
  58.             public void run() {  
  59.                 // 接口地址  
  60.                 String path&#61; "http://192.168.1.114/login.php";  
  61. //                String path&#61; "http://192.168.1.40/login.php";  
  62.                 try {  
  63.                     URL url &#61; new URL(path);  
  64.                     // 打开http链接  
  65.                     HttpURLConnection conn &#61; (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.                     // 对服务器端读取或者写入数据&#xff08;使用输入输出流&#xff09;  
  74.                     // 获取连接的输出流  
  75.                     DataOutputStream dos &#61; new DataOutputStream(conn.getOutputStream());  
  76.                     // action&#61;login 表示登陆 也可以等于别的 主要看你的php同事如何协商  
  77.                     // 一般来说 action&#61;login 表示登陆 action&#61;update 表示修改密码 不多赘述  
  78.                     // 接口php同事怎么写你就怎么传  
  79.                     dos.writeBytes("action&#61;"&#43; URLEncoder.encode("login","UTF8"));  
  80.                     dos.writeBytes("&username&#61;"&#43; URLEncoder.encode(userName,"UTF8"));  
  81.                     dos.writeBytes("&password&#61;"&#43; URLEncoder.encode(passWord,"UTF8"));  
  82.                     dos.flush();  
  83.                     dos.close();  
  84.                     // 从服务器获取相应数据  
  85.                     BufferedReader br &#61; new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  86.                     String result &#61; br.readLine();  
  87.                     System.out.println("result &#61;&#61; " &#43; result);  
  88.                     br.close();  
  89.                     conn.disconnect();  
  90.                     // 通过handler把result传出去  
  91.                     Message msg &#61; 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 weakReference;   // 软引用  
  105.         public MyHandler(MainActivity mainActivity){  
  106.             weakReference &#61; new WeakReference(mainActivity);  
  107.         }  
  108.         &#64;Override  
  109.         public void handleMessage(Message msg) {  
  110.             MainActivity mainActivity &#61; weakReference.get();  
  111.             if (mainActivity!&#61;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. }  










转载请注明出处&#xff1a;
http://blog.csdn.net/iwanghang/article/details/70685334








欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android&#xff0c;请与我联系
联系方式

微信&#xff1a;iwanghang
QQ&#xff1a;413711276
邮箱&#xff1a;iwanghang&#64;qq.com


推荐阅读
author-avatar
江山代有人2502914563
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有