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

Java 讀取網頁內容的兩種主流方式:HttpClient 與 HttpURLConnection

     編輯:Java 相關知識

Java 擷取遠端網頁/介面資料,常用方案有二:Apache HttpClient(功能豐富、支援連接池、Cookie 管理)與 JDK 內建 HttpURLConnection(零依賴、輕量)。本文提供兩者的 POST 請求完整代碼範本,並說明編碼處理、超時設定等實戰細節。

方案一:Apache HttpClient(推薦企業級專案)

public static String createHttpClient(String url, String param) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);

    // 參數編碼處理(目標頁為 GB2312,HTTP 傳輸用 ISO-8859-1)
    String keyWord = new String(param.getBytes("GB2312"), "ISO-8859-1");
    post.setRequestBody(new NameValuePair[] { new NameValuePair("keyword", keyWord) });

    int status = client.executeMethod(post);
    // 響應轉碼:ISO-8859-1 → GBK
    return new String(post.getResponseBodyAsString().getBytes("ISO-8859-1"), "GBK");
}

優勢:自動重定向、連接池、多執行緒安全、表單/檔案上傳、攔截器鏈。

方案二:JDK HttpURLConnection(零依賴、簡單場景)

public static String getPageContent(String strUrl, String strPostRequest, int maxLength) {
    StringBuffer buffer = new StringBuffer();
    System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
    System.setProperty("sun.net.client.defaultReadTimeout", "5000");

    URL url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (strPostRequest.length() > 0) {
        conn.setDoOutput(true);
        try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream())) {
            out.write(strPostRequest);
        }
    }

    try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        int ch;
        for (int len = 0; (ch = rd.read()) > -1 && (maxLength <= 0 || len < maxLength); len++) {
            buffer.append((char) ch);
        }
    } finally {
        conn.disconnect();
    }
    return buffer.toString().trim();
}

注意:JDK 11+ 建議遷移至 java.net.http.HttpClient(支援 HTTP/2、非阻塞、CompletableFuture)。

編碼處理黃金法則

  1. 請求參數:new String(param.getBytes(目標頁編碼), "ISO-8859-1")。
  2. 響應體:new String(bytes.getBytes("ISO-8859-1"), 目標頁編碼)。
  3. 若目標頁為 UTF-8,雙向統一用 UTF-8 即可避免亂碼。

選型建議

場景推薦方案
高併發、需連接池、Cookie、認證、重試Apache HttpClient / OkHttp
簡單爬蟲、無額外依賴限制、JDK 8/11HttpURLConnection / java.net.http.HttpClient
Android 專案OkHttp / Retrofit
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved