首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Apache HttpClient 核心用法與最佳實踐總結

     編輯:Java 綜合教學

Apache HttpClient 核心用法與最佳實踐總結

Apache HttpClient 是 Java 生態系中最廣泛使用的 HTTP 客戶端庫,支援 HTTP/1.1、連線池、自動重導向、Cookie 管理、認證、非同步請求等功能。本文整理核心用法與常見場景最佳實踐,助您快速上手。

1. Maven 依賴

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version> <!-- 或 5.x 版本 -->
</dependency>

2. 基本 GET 請求

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);
    }
}

3. POST 請求與 JSON 處理

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)) {
    // 處理回應...
}

4. 連線池與客戶端複用

生產環境務必複用 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();

5. 表單與檔案上傳

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());

6. 非同步請求

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(); // 阻塞等待
    // 處理回應...
}

7. 常見陷阱與建議

  • ✅ 使用 try-with-resources 確保回應與客戶端正確關閉
  • ✅ 設定合理的連線/讀取逾時,避免執行緒無限期阻塞
  • ✅ 複用客戶端實例,避免頻繁建立/銷毀連線池
  • ⚠️ 4.x 版本已進入維護模式,新專案建議使用 HttpClient 5.x(org.apache.httpcomponents.client5:httpclient5),API 更現代化並支援 HTTP/2

更多詳細範例請參考:HttpClient 使用詳解

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved