Apache HttpClient 5 核心用法詳解
Apache HttpClient 5 是 Apache 基金會推出的新一代 HTTP 客戶端庫,相比 4.x 版本在性能、模塊化和易用性上有顯著提升。以下是其核心用法及最佳實踐:
一、添加依賴
Maven 項目:
<dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.4-alpha1</version> <!-- 檢查最新版本 -->
</dependency>
Gradle 項目:
implementation 'org.apache.httpcomponents.client5:httpclient5:5.4-alpha1'
二、基礎用法
1. 創建 HttpClient 實例
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;// 創建帶連接池的客戶端(默認連接池大小:2*CPU核心數)
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManagerShared(true) // 共享連接池(推薦).setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(5000) // 連接超時(毫秒).setResponseTimeout(10000) // 響應超時.build()).build();
2. 發送 GET 請求
HttpGet httpGet = new HttpGet("https://api.example.com/data");try (CloseableHttpClient client = HttpClients.createDefault()) {try (CloseableHttpResponse response = client.execute(httpGet)) {HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("Status: " + response.getCode() + ", Body: " + result);}
}
3. 發送 POST 請求(提交 JSON)
HttpPost httpPost = new HttpPost("https://api.example.com/post");
String jsonBody = "{\"key\":\"value\"}";
httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));try (CloseableHttpClient client = HttpClients.createDefault()) {try (CloseableHttpResponse response = client.execute(httpPost)) {HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("Status: " + response.getCode() + ", Body: " + result);}
}
三、高級功能
1. 連接池配置(優化性能)
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); // 最大連接數
cm.setDefaultMaxPerRoute(20); // 每個路由默認最大連接數CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
2. 自定義 Header 和 Cookie
HttpGet httpGet = new HttpGet("https://api.example.com/data");
httpGet.setHeader("User-Agent", "Apache HttpClient 5");
httpGet.setHeader("Authorization", "Bearer token123");// 添加 Cookie
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("session_id", "abc123");
cookie.setDomain("api.example.com");
cookieStore.addCookie(cookie);CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
3. 文件上傳(Multipart)
HttpPost httpPost = new HttpPost("https://api.example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("path/to/file.jpg"), ContentType.MULTIPART_FORM_DATA, "file.jpg");
builder.addTextBody("description", "Test upload", ContentType.TEXT_PLAIN);httpPost.setEntity(builder.build());try (CloseableHttpClient client = HttpClients.createDefault()) {try (CloseableHttpResponse response = client.execute(httpPost)) {// 處理響應}
}
4. 異步請求(非阻塞)
HttpClientAsyncClient asyncClient = HttpClients.createAsyncDefault();HttpGet httpGet = new HttpGet("https://api.example.com/data");
asyncClient.execute(httpGet, new FutureCallback<>() {@Overridepublic void completed(ClassicHttpResponse response) {HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("Async Response: " + result);}@Overridepublic void failed(Exception ex) {ex.printStackTrace();}@Overridepublic void cancelled() {System.out.println("Request cancelled");}
});// 主線程繼續執行其他任務
Thread.sleep(5000); // 等待異步結果(實際需用 CountDownLatch 等機制)
四、遷移指南(從 HttpClient 4.x)
-
包名變化:
org.apache.http.client.HttpClient
?→?org.apache.hc.client5.http.classic.HttpClient
HttpGet
/HttpPost
?等類路徑調整。
-
API 調整:
- 響應處理:
CloseableHttpResponse
?替代?CloseableHttpResponse
(方法名類似)。 - 連接池管理:使用?
PoolingHttpClientConnectionManager
?替代?PoolingHttpClientConnectionManager
。
- 響應處理:
-
移除廢棄方法:
- 如?
HttpClientBuilder.setMaxConnPerRoute()
?改為?setMaxConnPerRoute(Route, int)
。
- 如?
五、最佳實踐
- 復用 HttpClient 實例:避免頻繁創建/銷毀,推薦使用?
HttpClients.custom().build()
?創建單例。 - 資源釋放:使用?
try-with-resources
?確保?CloseableHttpClient
?和?CloseableHttpResponse
?正確關閉。 - 異常處理:捕獲?
IOException
?和?HttpRequestException
,處理網絡錯誤和 HTTP 狀態碼。 - 性能監控:通過?
ConnectionStats
?監控連接池使用情況。
通過以上內容,您已掌握 Apache HttpClient 5 的核心用法,可根據項目需求實現高效、穩定的 HTTP 通信。如需處理復雜場景(如 OAuth2 認證、WebSocket),可進一步探索其擴展模塊。