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

Apache HttpClient 在 Java 項目中的完整應用指南

     編輯:Java 相關知識

簡介

Apache HttpClient 是 Apache Jakarta Commons 子項目,提供高效、功能豐富的 HTTP 協議客戶端編程支持。相比 JDK 原生 URLConnection,它在易用性、靈活性、連接管理、認證機制等方面優勢明顯,廣泛應用於 Cactus、HTMLUnit 等知名開源項目。

核心特性

  • 純 Java 實現,支持 HTTP/1.0 和 HTTP/1.1
  • 面向對象結構封裝所有 HTTP 方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE)
  • 支持 HTTPS、HTTP 代理、隧道代理、多種認證方案
  • 連接管理器支持多線程、最大連接數、過期連接清理
  • 自動 Cookie 管理、Keep-Alive 長連接、流式輸入輸出

基本使用流程

  1. 創建 CloseableHttpClient 實例
  2. 構建請求對象(HttpGet/HttpPost 等)並設置 URL
  3. 設置請求參數或實體(setEntity/setParams)
  4. 調用 execute() 發送請求獲取 CloseableHttpResponse
  5. 解析響應頭與響應實體(HttpEntity)
  6. 釋放連接資源(finally 塊中關閉)

代碼示例(基於 HttpClient 4.3+)

GET 請求

public void get() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet("https://www.baidu.com/");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println(EntityUtils.toString(entity));
            }
        } finally { response.close(); }
    } catch (Exception e) { e.printStackTrace(); }
    finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } }
}

POST 表單提交

public void postForm() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://localhost:8080/login");
    List formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("username", "admin"));
    formparams.add(new BasicNameValuePair("password", "123456"));
    httppost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
    // execute 並處理響應...
}

SSL 雙向認證

public void ssl() {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(new FileInputStream("d:\\tomcat.keystore"), "123456".toCharArray());
    SSLContext sslcontext = SSLContexts.custom()
        .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
        new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    // 執行 HTTPS 請求...
}

文件上傳

public void upload() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://localhost:8080/upload");
    FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
    StringBody comment = new StringBody("備註", ContentType.TEXT_PLAIN);
    HttpEntity reqEntity = MultipartEntityBuilder.create()
        .addPart("bin", bin).addPart("comment", comment).build();
    httppost.setEntity(reqEntity);
    // execute 並處理響應...
}

最佳實踐建議

  • 使用連接池管理器(PoolingHttpClientConnectionManager)提升多線程性能
  • 設置合理的連接超時、Socket 超時、請求超時
  • 統一異常處理與資源釋放,避免連接洩漏
  • 對於頻繁調用的服務,考慮復用 HttpClient 實例
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved