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

HttpClient 還是 HttpURLConnection?一句話給答案

編輯:Android 程式設計入門

結論:用 HttpURLConnection。

為什么

在 Android 2.2 及更早版本中,HttpClient 的 bug 較少,是當時更穩妥的選擇。而從 Android 2.3 開始,HttpURLConnection 成為官方推薦方案——它的底層实现被 switched 到 OkHttp 之后,性能和穩定性都有了明顯提升,HttpClient 則逐漸停止維護,并已在 API 22 中被標記為廢棄。

它的優勢

  • API 更簡單,體積更小,沒有額外的 jar 依賴。
  • 內置的壓縮與緩存機制能有效減少網絡流量,對同一地址的請求復用底層連接。
  • 在提升響應速度與降低電量消耗上都有實際收益。

最小使用示例

HttpURLConnection conn = null;
try {
    URL url = new URL("https://api.example.com/data");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        String result = new String(baos.toByteArray(), "UTF-8");
        // 后續解析 result
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (conn != null) conn.disconnect();
}

實戰提醒

  • 超時時間一定要設置,默認是無限等待,網絡異常時會把線程一直掛住。
  • 記得在 finally 里 disconnect,并關閉 InputStream,否則連接無法被復用。
  • POST 請求需要 setDoOutput(true) 并寫入 getOutputStream()。
  • 如果項目里只需要簡單的 GET/POST,后續也可以考慮 OkHttp——它對連接池、攔截器、HTTP/2 的支持更完善,如今已是事實上的標准選擇。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved