Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

談談 Android 的三種網路通信方式

編輯:關於 Android 程式設計

Android 平台主要提供三套網路 API:java.net.*(標準 Java 介面)、org.apache 介面,以及 android.net.*(Android 專屬介面)。以下分別說明各自的定位與用法。

一、標準 Java 介面 java.net.*

這個套件提供與联网相關的基礎類,包含串流、Socket、Internet 協定與常見的 HTTP 處理,例如建立 URL、URLConnection/HttpURLConnection、設定連線參數、寫入與讀取資料等。以下用一個最經典的 Socket 回聲範例說明。

服務端:

 public class Server implements Runnable{ @Override public void run() { Socket socket = null; try { ServerSocket server = new ServerSocket(18888); //循環監聽客戶端鏈接請求 while(true){ System.out.println("start..."); //接收請求 socket = server.accept(); System.out.println("accept..."); //接收客戶端消息 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = in.readLine(); //發送消息,向客戶端 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); out.println("Server:" + message); //關閉流 in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); }finally{ if (null != socket){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //啟動服務器 public static void main(String[] args){ Thread server = new Thread(new Server()); server.start(); } } 

客戶端 MainActivity:

 public class MainActivity extends Activity { private EditText editText; private Button button; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText)findViewById(R.id.editText1); button = (Button)findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Socket socket = null; String message = editText.getText().toString()+ "\r\n" ; try { //創建客戶端socket,注意:不能用localhost或127.0.0.1,Android模擬器把自己作為localhost socket = new Socket("<span >10.0.2.2</span>",18888); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter (socket.getOutputStream())),true); //發送數據 out.println(message); //接收數據 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = in.readLine(); if (null != msg){ editText.setText(msg); System.out.println(msg); } else{ editText.setText("data error"); } out.close(); in.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if (null != socket){ socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }); } } 

版面配置:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:layout_width="match_parent" android:id="@+id/editText1" android:layout_height="wrap_content" android:hint="input the message and click the send button" ></EditText> <Button android:text="send" android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button> </LinearLayout> 

啟動服務端:

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

執行結果:

連線失敗時,可以先檢查三件事:

是否已加入網路權限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
模擬器連本機服務必須使用 10.0.2.2,而非 localhost 或 127.0.0.1
模擬器無法配置代理

二、Apache 介面(HttpClient)

對大多數應用來說,JDK 自带的網路能力往往不夠用,這時就需要 Android 提供的 Apache HttpClient。它是開源專案,為 HTTP 客戶端編程提供了更高效、功能更完整的工具包。

先在機器上建一個 web 應用 myapp,內含最簡單的 http.jsp:

 <%@page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title> Http Test </title> </head> <body> <% String type = request.getParameter("parameter"); String result = new String(type.getBytes("iso-8859-1"),"utf-8"); out.println("<h1>" + result + "</h1>"); %> </body> </html> 

接著在 Android 端分別用 GET 與 POST 去拜訪它。版面配置:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:gravity="center" android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> <Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> </LinearLayout> 

strings.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">通過按鈕選擇不同方式訪問網頁</string> <string name="app_name">Http Get</string> </resources>

主 Activity:

 public class MainActivity extends Activity { private TextView textView; private Button get,post; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textView); get = (Button)findViewById(R.id.get); post = (Button)findViewById(R.id.post); //綁定按鈕監聽器 get.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //注意:此處ip不能用127.0.0.1或localhost,Android模擬器已將它自己作為了localhost String uri = "https://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式發送請求"; textView.setText(get(uri)); } }); //綁定按鈕監聽器 post.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String uri = "https://192.168.22.28:8080/myapp/http.jsp"; textView.setText(post(uri)); } }); } /** * 以get方式發送請求,訪問web * @param uri web地址 * @return 響應數據 */ private static String get(String uri){ BufferedReader reader = null; StringBuffer sb = null; String result = ""; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(uri); try { //發送請求,得到響應 HttpResponse response = client.execute(request); //請求成功 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); sb = new StringBuffer(); String line = ""; String NL = System.getProperty("line.separator"); while((line = reader.readLine()) != null){ sb.append(line); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if (null != reader){ reader.close(); reader = null; } } catch (IOException e) { e.printStackTrace(); } } if (null != sb){ result = sb.toString(); } return result; } /** * 以post方式發送請求,訪問web * @param uri web地址 * @return 響應數據 */ private static String post(String uri){ BufferedReader reader = null; StringBuffer sb = null; String result = ""; HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(uri); //保存要傳遞的參數 List<NameValuePair> params = new ArrayList<NameValuePair>(); //添加參數 params.add(new BasicNameValuePair("parameter","以Post方式發送請求")); try { //設置字符集 HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8"); //請求對象 request.setEntity(entity); //發送請求 HttpResponse response = client.execute(request); //請求成功 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ System.out.println("post success"); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); sb = new StringBuffer(); String line = ""; String NL = System.getProperty("line.separator"); while((line = reader.readLine()) != null){ sb.append(line); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { //關閉流 if (null != reader){ reader.close(); reader = null; } } catch (IOException e) { e.printStackTrace(); } } if (null != sb){ result = sb.toString(); } return result; } } 

執行結果:

三、android.net 套件

這個套件常用於 Android 特有的網路編程,例如存取 WiFi 狀態、查詢联网資訊、寄送郵件等,本文不再展開。

最後補充一個現實提醒:HttpClient 自 Android 6.0 起已被移除,DefaultHttpClient 在新專案上無法直接使用,目前應改用 HttpURLConnection、OkHttp 或 Retrofit。上面範例的價值在於理解 GET/POST 的請求組成邏輯,而非直接複製到新專案。此外,所有網路操作都必須放在子執行緒中,不能在主執行緒同步呼叫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved