Apache HttpClient 是 Java 生態系中最廣泛使用的 HTTP 客戶端庫,支援 HTTP/1.1、連線池、自動重導向、Cookie 管理、認證、非同步請求等功能。本文整理核心用法與常見場景最佳實踐,助您快速上手。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version> <!-- 或 5.x 版本 -->
</dependency>
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet get = new HttpGet("https://api.example.com/users/1");
try (CloseableHttpResponse resp = client.execute(get)) {
String body = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
System.out.println("Status: " + resp.getStatusLine().getStatusCode());
System.out.println("Body: " + body);
}
}
HttpPost post = new HttpPost("https://api.example.com/users");
post.setHeader("Content-Type", "application/json");
String json = "{\"name\":\"Alice\",\"age\":30}";
post.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
try (CloseableHttpResponse resp = client.execute(post)) {
// 處理回應...
}
生產環境務必複用 CloseableHttpClient 實例,並配置連線池:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(50);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(config)
.evictIdleConnections(60, TimeUnit.SECONDS)
.build();
HttpPost post = new HttpPost("https://api.example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "alice");
builder.addBinaryBody("file", new File("photo.jpg"), ContentType.APPLICATION_OCTET_STREAM, "photo.jpg");
post.setEntity(builder.build());
try (CloseableHttpAsyncClient asyncClient = HttpAsyncClients.createDefault()) {
asyncClient.start();
HttpGet get = new HttpGet("https://api.example.com/data");
Future<HttpResponse> future = asyncClient.execute(get, null);
HttpResponse resp = future.get(); // 阻塞等待
// 處理回應...
}
try-with-resources 確保回應與客戶端正確關閉org.apache.httpcomponents.client5:httpclient5),API 更現代化並支援 HTTP/2更多詳細範例請參考:HttpClient 使用詳解