Java 擷取遠端網頁/介面資料,常用方案有二:Apache HttpClient(功能豐富、支援連接池、Cookie 管理)與 JDK 內建 HttpURLConnection(零依賴、輕量)。本文提供兩者的 POST 請求完整代碼範本,並說明編碼處理、超時設定等實戰細節。
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");
}
優勢:自動重定向、連接池、多執行緒安全、表單/檔案上傳、攔截器鏈。
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)。
new String(param.getBytes(目標頁編碼), "ISO-8859-1")。new String(bytes.getBytes("ISO-8859-1"), 目標頁編碼)。| 場景 | 推薦方案 |
|---|---|
| 高併發、需連接池、Cookie、認證、重試 | Apache HttpClient / OkHttp |
| 簡單爬蟲、無額外依賴限制、JDK 8/11 | HttpURLConnection / java.net.http.HttpClient |
| Android 專案 | OkHttp / Retrofit |