HTTP 協議是互聯網基石,Java 提供了標準庫 HttpURLConnection 與 Apache 開源 HttpClient 兩大客戶端選擇。本文從 API 設計、功能完備性、適用場景三個維度深度對比,並給出 Android、爬蟲、微服務調用等典型場景的選型建議。
getResponseCode() / getResponseMessage():響應狀態setRequestMethod(String):GET/POST/PUT/DELETEgetInputStream() / getOutputStream():流式讀寫Set-Cookie 標頭、維護 CookieStore。BasicCookieStore + HttpClientContext 實現瀏覽器級會話保持。PoolingHttpClientConnectionManager 復用連接,大幅提升吞吐。CloseableHttpClient + HttpAsyncClient 覆蓋同步異步場景。// HttpClient 幾行搞定
CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(new BasicCookieStore())
.build();
HttpPost login = new HttpPost("https://example.com/login");
login.setEntity(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("user", "admin"),
new BasicNameValuePair("pass", "123456"))));
client.execute(login); // 自動保存 Session Cookie
HttpGet protected = new HttpGet("https://example.com/admin");
String html = EntityUtils.toString(client.execute(protected).getEntity());
同等邏輯用 HttpURLConnection 需 50+ 行代碼手動處理 Cookie、重定向、編碼。
org.apache.http.legacy,但已標註棄用,Google 強推 HttpURLConnection 或 OkHttp。| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 簡單 GET/POST,無會話,低併發 | HttpURLConnection | 零依賴,啟動快 |
| 需登錄態、Cookie 持久化 | HttpClient / OkHttp | 自動會話管理 |
| 高併發微服務調用 | HttpClient + 連接池 / OkHttp | 連接復用、熔斷、重試 |
| 爬蟲/大規模抓取 | HttpClient / OkHttp (異步) | 攔截器、代理、限流 |
| Android 新項目 | OkHttp / Retrofit | 官方推薦、Kotlin 友好 |
| 舊系統維護,不可引入新依賴 | HttpURLConnection | 兼容性最好 |
EntityUtils.consumeQuietly() 或 inputStream.close() 釋放連接回池。setConnectTimeout / setReadTimeout 必須顯式配置,防止線程掛死。TrustAll 策略,導入正規 CA 證書或配置 SSLContext。HttpURLConnection 是「瑞士軍刀」——輕便但功能有限;HttpClient 是「專業工具箱」——功能全、學習曲線稍陡。現代 Java 開發中,OkHttp 兼具兩者優勢且 API 更優雅,已成首選。理解兩者核心差異,能在受限環境(如無法引入三方庫)做出正確妥協,也能在架構選型時理直氣壯地推薦最佳方案。