1. 程式人生 > >Android的三種網路通訊方式

Android的三種網路通訊方式

Android平臺有三種網路介面可以使用,他們分別是:java.net.*(標準Java介面)、Org.apache介面和Android.net.*(Android網路介面)。下面分別介紹這些介面的功能和作用。
1.標準Java介面
java.net.*提供與聯網有關的類,包括流、資料包套接字(socket)、Internet協議、常見Http處理等。比如:建立URL,以及URLConnection/HttpURLConnection物件、設定連結引數、連結到伺服器、向伺服器寫資料、從伺服器讀取資料等通訊。這些在Java網路程式設計中均有涉及,我們看一個簡單的socket程式設計,實現伺服器回發客戶端資訊。
服務端:
  1. publicclass Server implements Runnable{  
  2.     @Override
  3.     publicvoid 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.     publicstaticvoid main(String[] args){  
  37.         Thread server = new Thread(new Server());  
  38.         server.start();  
  39.     }  
  40. }  

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

佈局檔案:
  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. publicclass MainActivity extends Activity {  
  2.     private TextView textView;  
  3.     private Button get,post;  
  4.     /** Called when the activity is first created. */
  5.     @Override
  6.     publicvoid onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.main);  
  9.         textView = (TextView)findViewById(R.id.textView);  
  10.         get = (Button)findViewById(R.id.get);  
  11.         post = (Button)findViewById(R.id.post);  
  12.         //繫結按鈕監聽器
  13.         get.setOnClickListener(new OnClickListener() {  
  14.             @Override
  15.             publicvoid onClick(View v) {  
  16.                 //注意:此處ip不能用127.0.0.1或localhost,Android模擬器已將它自己作為了localhost
  17.                 String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式傳送請求";  
  18.                 textView.setText(get(uri));  
  19.             }  
  20.         });  
  21.         //繫結按鈕監聽器
  22.         post.setOnClickListener(new OnClickListener() {  
  23.             @Override
  24.             publicvoid onClick(View v) {  
  25.                 String uri = "http://192.168.22.28:8080/myapp/http.jsp";  
  26.                 textView.setText(post(uri));  
  27.             }  
  28.         });  
  29.     }  
  30.     /** 
  31.      * 以get方式傳送請求,訪問web 
  32.      * @param uri web地址 
  33.      * @return 響應資料 
  34.      */
  35.     privatestatic String get(String uri){  
  36.         BufferedReader reader = null;  
  37.         StringBuffer sb = null;  
  38.         String result = "";  
  39.         HttpClient client = new DefaultHttpClient();  
  40.         HttpGet request = new HttpGet(uri);  
  41.         try {  
  42.             //傳送請求,得到響應
  43.             HttpResponse response = client.execute(request);  
  44.             //請求成功
  45.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
  46.                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
  47.                 sb = new StringBuffer();  
  48.                 String line = "";  
  49.                 String NL = System.getProperty("line.separator");  
  50.                 while((line = reader.readLine()) != null){  
  51.                     sb.append(line);  
  52.                 }  
  53.             }  
  54.         } catch (ClientProtocolException e) {  
  55.             e.printStackTrace();  
  56.         } catch (IOException e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.         finally{  
  60.             try {  
  61.                 if (null != reader){  
  62.                     reader.close();  
  63.                     reader = null;  
  64.                 }  
  65.             } catch (IOException e) {  
  66.                 e.printStackTrace();  
  67.             }  
  68.         }  
  69.         if (null != sb){  
  70.             result =  sb.toString();  
  71.         }  
  72.         return result;  
  73.     }  
  74.     /** 
  75.      * 以post方式傳送請求,訪問web 
  76.      * @param uri web地址 
  77.      * @return 響應資料 
  78.      */
  79.     privatestatic String post(String uri){  
  80.         BufferedReader reader = null;  
  81.         StringBuffer sb = null;  
  82.         String result = "";  
  83.         HttpClient client = new DefaultHttpClient();  
  84.         HttpPost request = new HttpPost(uri);  
  85.         //儲存要傳遞的引數
  86.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  87.         //新增引數
  88.         params.add(new BasicNameValuePair("parameter","以Post方式傳送請求"));  
  89.         try {  
  90.             //設定字符集
  91.             HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");  
  92.             //請求物件
  93.             request.setEntity(entity);  
  94.             //傳送請求
  95.             HttpResponse response = client.execute(request);  
  96.             //請求成功
  97.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
  98.                 System.out.println("post success");  
  99.                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
  100.                 sb = new StringBuffer();  
  101.                 String line = "";  
  102.                 String NL = System.getProperty("line.separator");  
  103.                 while((line = reader.readLine()) != null){  
  104.                     sb.append(line);  
  105.                 }  
  106.             }  
  107.         } catch (ClientProtocolException e) {  
  108.             e.printStackTrace();  
  109.         } catch (IOException e) {  
  110.             e.printStackTrace();  
  111.         }  
  112.         finally{  
  113.             try {  
  114.                 //關閉流
  115.                 if (null != reader){  
  116.                     reader.close();  
  117.                     reader = null;  
  118.                 }  
  119.             } catch (IOException e) {  
  120.                 e.printStackTrace();  
  121.             }  
  122.         }  
  123.         if (null != sb){  
  124.             result =  sb.toString();  
  125.         }  
  126.         return result;  
  127.     }  
  128. }  

執行結果如下:

3.android.net程式設計:
常常使用此包下的類進行Android特有的網路程式設計,如:訪問WiFi,訪問Android聯網資訊,郵件等功能。這裡不詳細講。