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

Android 中的 HttpClient 網路通訊實作

編輯:關於 Android 程式設計

在 Android 開發中,我們經常需要與伺服器進行資料交換的網路功能。為此,Android SDK 提供了 Apache 的 HttpClient,方便我們操作各種 HTTP 服務。

先看一段最簡要的範例程式碼:

   HttpClient httpClient = new DefaultHttpClient();
   // 建立一個 Get 請求
 HttpGet request  = new HttpGet("uri");
  // 發送 GET 請求,並將響應內容轉換成字串
        String response = httpclient.execute(request, new BasicResponseHandler());
        Log.v("response text", response);

這只是示範用程式碼,實際專案中的請求與響應處理會更複雜,還要兼顧容錯性,但那並非本文重點。

為何要用單例的 HttpClient?

發出 HTTP 請求前,我們先建立了一個 HttpClient 物件。在實際專案中,往往有多處需要進行 HTTP 通訊,此時不必為每個請求都建立新的 HttpClient。因為 HttpClient 就像一個小型瀏覽器,對整個應用而言,一個實例就已足夠。直覺做法是寫成單例:

public class CustomerHttpClient {
    private static HttpClient customerHttpClient;
   
    private CustomerHttpClient() {
    }
   
    public static HttpClient getHttpClient() {
        if(null == customerHttpClient) {
            customerHttpClient = new DefaultHttpClient();
        }
        return customerHttpClient;
    }
}

但當多個請求(請求 A、請求 B)需要同時處理時,該怎麼辦?我們改用多執行緒來解決,而執行緒安全的問題,HttpClient 本身已經幫我們處理好了。

public class CustomerHttpClient {
    private static final String CHARSET = HTTP.UTF_8;
    private static HttpClient customerHttpClient;

    private CustomerHttpClient() {
    }

    public static synchronized HttpClient getHttpClient() {
        if (null == customerHttpClient) {
            HttpParams params = new BasicHttpParams();
            // 設置一些基本參數
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, CHARSET);
            HttpProtocolParams.setUseExpectContinue(params, true);
            HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
            // 超時設置
            ConnManagerParams.setTimeout(params, 1000);
            HttpConnectionParams.setConnectionTimeout(params, 2000);
            HttpConnectionParams.setSoTimeout(params, 4000);
            // 設置我們的HttpClient支持HTTP和HTTPS兩種模式
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            // 使用線程安全的連接管理來創建HttpClient
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
            customerHttpClient = new DefaultHttpClient(conMgr, params);
        }
        return customerHttpClient;
    }
}

在 getHttpClient() 方法中,我們為 HttpClient 設定了基本參數與超時,並用 ThreadSafeClientConnManager 建立執行緒安全的 HttpClient。

HttpClient 的三種超時

ConnManagerParams.setTimeout(params, 1000):從連接池中取連接的超時時間,此處設為 1 秒。

HttpConnectionParams.setConnectionTimeout(params, 2000):透過網路與伺服器建立連接的超時時間。HttpClient 會用一個非同步執行緒建立與伺服器的 socket 連接,這就是該 socket 連接的超時時間,此處設為 2 秒。

HttpConnectionParams.setSoTimeout(params, 4000):Socket 讀取資料的超時時間,也就是從伺服器取得響應資料所需等待的時間,此處設為 4 秒。

以上三種超時分別會拋出 ConnectionPoolTimeoutException、ConnectionTimeoutException 與 SocketTimeoutException。

封裝簡單的 POST 請求

有了單例的 HttpClient,我們就能把常用的 GET、POST 請求程式碼封裝進工具類。以下先實作發送 POST 請求並返回響應字串的方法,加入 CustomerHttpClient 類別中:

private static final String TAG = "CustomerHttpClient";

public static String post(String url, NameValuePair... params) {
        try {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // 請求參數
            for (NameValuePair p : params) {
                formparams.add(p);
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, CHARSET);
            HttpPost request = new HttpPost(url);
            request.setEntity(entity);
            HttpClient client = getHttpClient();
            HttpResponse response = client.execute(request);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException("請求失敗");
            }
            HttpEntity resEntity =  response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, e.getMessage());
            return null;
        } catch (ClientProtocolException e) {
            Log.w(TAG, e.getMessage());
            return null;
        } catch (IOException e) {
            throw new RuntimeException("連接失敗", e);
        }
    }

有了這個工具類,整個專案都能方便地進行網路通訊。以下示範以 username 與 password 註冊帳戶並取得新帳戶 ID:

final String url = "https://yourdomain/context/adduser";
    NameValuePair param1 = new BasicNameValuePair("username", "張三");
    NameValuePair param2 = new BasicNameValuePair("password", "123456");
    int resultId = -1;
    try {
        String response = CustomerHttpClient.post(url, param1, param2);
        JSONObject root = new JSONObject(response);
        resultId = Integer.parseInt(root.getString("userid"));
        Log.i(TAG, "新用戶ID:" + resultId);
    } catch (RuntimeException e) {
        Log.w(TAG, e.getMessage());
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }

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