首页 > 代码库 > 【Android笔记】Android的三种网络通信方式

【Android笔记】Android的三种网络通信方式

Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口)、Org.apache接口和Android.net.*(Android网络接口)。下面分别介绍这些接口的功能和作用。

1.标准Java接口
java.net.*提供与联网有关的类,包括流、数据包套接字(socket)、Internet协议、常见Http处理等。比如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java网络编程中均有涉及,我们看一个简单的socket编程,实现服务器回发客户端信息。
服务端:

 1 public class Server implements Runnable{   2     @Override   3     public void run() {   4         Socket socket = null;   5         try {   6             ServerSocket server = new ServerSocket(18888);   7             //循环监听客户端链接请求   8             while(true){   9                 System.out.println("start...");  10                 //接收请求  11                 socket = server.accept();  12                 System.out.println("accept...");  13                 //接收客户端消息  14                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  15                 String message = in.readLine();  16                 //发送消息,向客户端  17                 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);  18                 out.println("Server:" + message);  19                 //关闭流  20                 in.close();  21                 out.close();  22             }  23         } catch (IOException e) {  24             e.printStackTrace();  25         }finally{  26             if (null != socket){  27                 try {  28                     socket.close();  29                 } catch (IOException e) {  30                     e.printStackTrace();  31                 }  32             }  33         }  34           35     }  36     //启动服务器  37     public static void main(String[] args){  38         Thread server = new Thread(new Server());  39         server.start();  40     }  41 }  

客户端,MainActivity

 1 public class MainActivity extends Activity {   2     private EditText editText;   3     private Button button;   4     /** Called when the activity is first created. */   5     @Override   6     public void onCreate(Bundle savedInstanceState) {   7         super.onCreate(savedInstanceState);   8         setContentView(R.layout.main);   9           10         editText = (EditText)findViewById(R.id.editText1);  11         button = (Button)findViewById(R.id.button1);  12           13         button.setOnClickListener(new OnClickListener() {  14             @Override  15             public void onClick(View v) {  16                 Socket socket = null;  17                 String message = editText.getText().toString()+ "\r\n" ;  18                 try {  19                     //创建客户端socket,注意:不能用localhost或127.0.0.1,Android模拟器把自己作为localhost  20                     socket = new Socket("<span style="font-weight: bold;">10.0.2.2</span>",18888);  21                     PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter  22                             (socket.getOutputStream())),true);  23                     //发送数据  24                     out.println(message);  25                       26                     //接收数据  27                     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  28                     String msg = in.readLine();  29                     if (null != msg){  30                         editText.setText(msg);  31                         System.out.println(msg);  32                     }  33                     else{  34                         editText.setText("data error");  35                     }  36                     out.close();  37                     in.close();  38                 } catch (UnknownHostException e) {  39                     e.printStackTrace();  40                 } catch (IOException e) {  41                     e.printStackTrace();  42                 }  43                 finally{  44                     try {  45                         if (null != socket){  46                             socket.close();  47                         }  48                     } catch (IOException e) {  49                         e.printStackTrace();  50                     }  51                 }  52             }  53         });  54     }  55 }  

布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>   2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   3     android:orientation="vertical" android:layout_width="fill_parent"   4     android:layout_height="fill_parent">   5     <TextView android:layout_width="fill_parent"   6         android:layout_height="wrap_content" android:text="@string/hello" />   7     <EditText android:layout_width="match_parent" android:id="@+id/editText1"   8         android:layout_height="wrap_content"   9         android:hint="input the message and click the send button"  10         ></EditText>  11     <Button android:text="send" android:id="@+id/button1"  12         android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>  13 </LinearLayout>  

启动服务器:

1 javac com/test/socket/Server.java  2 java com.test.socket.Server  

运行客户端程序:

结果如图:

注意:服务器与客户端无法链接的可能原因有:
没有加访问网络的权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模拟器不能配置代理。

 

2。Apache接口

对于大部分应用程序而言JDK本身提供的网络功能已远远不够,这时就需要Android提供的Apache HttpClient了。它是一个开源项目,功能更加完善,为客户端的Http编程提供高效、最新、功能丰富的工具包支持。
下面我们以一个简单例子来看看如何使用HttpClient在Android客户端访问Web。
首先,要在你的机器上搭建一个web应用myapp,只有很简单的一个http.jsp
内容如下:

 1 <%@page language="java" import="java.util.*" pageEncoding="utf-8"%>   2 <html>   3 <head>   4 <title>   5 Http Test   6 </title>   7 </head>   8 <body>   9 <%  10 String type = request.getParameter("parameter");  11 String result = new String(type.getBytes("iso-8859-1"),"utf-8");  12 out.println("<h1>" + result + "</h1>");  13 %>  14 </body>  15 </html>  

然后实现Android客户端,分别以post、get方式去访问myapp,代码如下:
布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>   2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   3     android:orientation="vertical"   4     android:layout_width="fill_parent"   5     android:layout_height="fill_parent"   6     >   7 <TextView   8     android:gravity="center"   9     android:id="@+id/textView"    10     android:layout_width="fill_parent"  11     android:layout_height="wrap_content"  12     android:text="@string/hello"  13     />  14 <Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>  15 <Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>  16 </LinearLayout>  

资源文件:
strings.xml

1 <?xml version="1.0" encoding="utf-8"?>  2 <resources>  3     <string name="hello">通过按钮选择不同方式访问网页</string>  4     <string name="app_name">Http Get</string>  5 </resources>  

主Activity:

  1 public class MainActivity extends Activity {    2     private TextView textView;    3     private Button get,post;    4     /** Called when the activity is first created. */    5     @Override    6     public void onCreate(Bundle savedInstanceState) {    7         super.onCreate(savedInstanceState);    8         setContentView(R.layout.main);    9            10         textView = (TextView)findViewById(R.id.textView);   11         get = (Button)findViewById(R.id.get);   12         post = (Button)findViewById(R.id.post);   13            14         //绑定按钮监听器   15         get.setOnClickListener(new OnClickListener() {   16             @Override   17             public void onClick(View v) {   18                 //注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost   19                 String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式发送请求";   20                 textView.setText(get(uri));   21             }   22         });   23         //绑定按钮监听器   24         post.setOnClickListener(new OnClickListener() {   25             @Override   26             public void onClick(View v) {   27                 String uri = "http://192.168.22.28:8080/myapp/http.jsp";   28                 textView.setText(post(uri));   29             }   30         });   31     }   32     /**  33      * 以get方式发送请求,访问web  34      * @param uri web地址  35      * @return 响应数据  36      */   37     private static String get(String uri){   38         BufferedReader reader = null;   39         StringBuffer sb = null;   40         String result = "";   41         HttpClient client = new DefaultHttpClient();   42         HttpGet request = new HttpGet(uri);   43         try {   44             //发送请求,得到响应   45             HttpResponse response = client.execute(request);   46                47             //请求成功   48             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   49                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));   50                 sb = new StringBuffer();   51                 String line = "";   52                 String NL = System.getProperty("line.separator");   53                 while((line = reader.readLine()) != null){   54                     sb.append(line);   55                 }   56             }   57         } catch (ClientProtocolException e) {   58             e.printStackTrace();   59         } catch (IOException e) {   60             e.printStackTrace();   61         }   62         finally{   63             try {   64                 if (null != reader){   65                     reader.close();   66                     reader = null;   67                 }   68             } catch (IOException e) {   69                 e.printStackTrace();   70             }   71         }   72         if (null != sb){   73             result =  sb.toString();   74         }   75         return result;   76     }   77     /**  78      * 以post方式发送请求,访问web  79      * @param uri web地址  80      * @return 响应数据  81      */   82     private static String post(String uri){   83         BufferedReader reader = null;   84         StringBuffer sb = null;   85         String result = "";   86         HttpClient client = new DefaultHttpClient();   87         HttpPost request = new HttpPost(uri);   88            89         //保存要传递的参数   90         List<NameValuePair> params = new ArrayList<NameValuePair>();   91         //添加参数   92         params.add(new BasicNameValuePair("parameter","以Post方式发送请求"));   93            94         try {   95             //设置字符集   96             HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");   97             //请求对象   98             request.setEntity(entity);   99             //发送请求  100             HttpResponse response = client.execute(request);  101               102             //请求成功  103             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  104                 System.out.println("post success");  105                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  106                 sb = new StringBuffer();  107                 String line = "";  108                 String NL = System.getProperty("line.separator");  109                 while((line = reader.readLine()) != null){  110                     sb.append(line);  111                 }  112             }  113         } catch (ClientProtocolException e) {  114             e.printStackTrace();  115         } catch (IOException e) {  116             e.printStackTrace();  117         }  118         finally{  119             try {  120                 //关闭流  121                 if (null != reader){  122                     reader.close();  123                     reader = null;  124                 }  125             } catch (IOException e) {  126                 e.printStackTrace();  127             }  128         }  129         if (null != sb){  130             result =  sb.toString();  131         }  132         return result;  133     }  134 }  

运行结果如下:

 

3.android.net编程:
常常使用此包下的类进行Android特有的网络编程,如:访问WiFi,访问Android联网信息,邮件等功能。这里不详细讲。

参考原文:http://blog.csdn.net/yuzhiboyi/article/details/7743390

【Android笔记】Android的三种网络通信方式