萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android HttpClient 工具類封裝:單例、執行緒安全、超時設定與 POST 封裝

為何需要單例 HttpClient?

HttpClient 相當於輕量級瀏覽器,內含連線池、Cookie Store、認證快取。全 App 共用單一實例可複用連線、減少資源消耗、統一配置。

執行緒安全單例實作


public class CustomerHttpClient {
    private static final String CHARSET = HTTP.UTF_8;
    private static HttpClient client;
    
    private CustomerHttpClient() {}
    
    public static synchronized HttpClient getHttpClient() {
        if (client == null) {
            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); // 建立 Socket 連線超時
            HttpConnectionParams.setSoTimeout(params, 4000);   // 讀取資料超時
            
            // 支援 HTTP/HTTPS
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            
            // 執行緒安全連線管理器
            ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry);
            client = new DefaultHttpClient(mgr, params);
        }
        return client;
    }
}

三種超時詳細解釋

ConnManagerParams.setTimeoutHttpConnectionParams.setConnectionTimeoutHttpConnectionParams.setSoTimeout
超時類型參數含義例外
連線池取連線從 ThreadSafeClientConnManager 取得可用連線的最長等待時間ConnectionPoolTimeoutException
建立連線TCP 三向交握、SSL 握手完成的最長時間ConnectTimeoutException
讀取資料Socket 等待伺服器回傳資料的最長時間SocketTimeoutException

封裝通用 POST 請求


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

使用範例


String url = "https://api.example.com/adduser";
NameValuePair p1 = new BasicNameValuePair("username", "張三");
NameValuePair p2 = new BasicNameValuePair("password", "123456");

try {
    String json = CustomerHttpClient.post(url, p1, p2);
    JSONObject obj = new JSONObject(json);
    int userId = obj.getInt("userid");
    Log.i(TAG, "新用戶 ID: " + userId);
} catch (RuntimeException e) {
    // 網路/HTTP 錯誤
} catch (JSONException e) {
    // 解析錯誤
}

現代化遷移建議

  • Android 6.0+ 移除 Apache HttpClient,建議遷移至 HttpURLConnection 或 OkHttp / Retrofit。
  • OkHttp 內建連線池、透明 GZIP、HTTP/2、攔截器,API 更現代、效能更優。
  • 若維護舊專案,本封裝仍可使用;新專務請直接採用 OkHttp/Retrofit。

掌握 HttpClient 封裝精髓,為遷移現代網路庫打下堅實基礎。

copyright © 萬盛學電腦網 all rights reserved