Java 抓取網頁內容常見兩種路徑:使用 Apache HttpClient(功能豐富、自動處理 Cookie/重定向)或 JDK 原生 HttpURLConnection(零依賴、輕量)。本文提供兩種完整可用示例,並處理編碼與 HTML 標簽清洗。
需引入依賴:httpclient、httpcore、commons-logging、commons-codec。
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.IOException;
public class HttpClientFetcher {
public static String fetchWithHttpClient(String url, String postParam) throws IOException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
// 如需 POST 參數
if (postParam != null) {
post.setRequestBody(new NameValuePair[]{new NameValuePair("keyword", postParam)});
}
int status = client.executeMethod(post);
if (status != HttpStatus.SC_OK) {
throw new IOException("HTTP 錯誤: " + status);
}
// 關鍵:按 ISO-8859-1 讀取再按目標編碼解碼
String raw = post.getResponseBodyAsString();
String decoded = new String(raw.getBytes("ISO-8859-1"), "GB2312"); // 根據目標頁面編碼調整
// 簡單清洗 HTML 標簽與實體
return decoded.replaceAll("&[a-zA-Z]{1,10};", "")
.replaceAll("<[^>]*>", "");
}
}
import java.io.*;
import java.net.*;
public class UrlConnectionFetcher {
public static String fetchWithUrlConnection(String urlStr, String postData, int maxLength) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 防 403
if (postData != null && !postData.isEmpty()) {
conn.setDoOutput(true);
try (OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) {
osw.write(postData);
}
}
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GB2312"))) {
int ch;
for (int len = 0; (ch = br.read()) != -1 && (maxLength <= 0 || len < maxLength); len++) {
sb.append((char) ch);
}
}
// 清洗
return sb.toString()
.replaceAll("&[a-zA-Z]{1,10};", "")
.replaceAll("<[^>]*>", "");
}
}
| 特性 | HttpClient | HttpURLConnection |
|---|---|---|
| 依賴 | 需外部 JAR | 零依賴 |
| Cookie 管理 | 自動 | 手動 |
| 重定向 | 自動 | 自動(可關閉) |
| 連接池 | 內建 | 無 |
| 代理支援 | 完善 | 需手動設置 |
| 適用場景 | 複雜爬蟲、生產系統 | 簡單抓取、受限環境 |
Content-Type Header 獲取 charset。<meta charset=...> 解析。new String(bytes, detectedCharset) 解碼,切勿硬編碼 ISO-8859-1 中轉(除非確定)。新項目建議使用 OkHttp 或 Jsoup:
Jsoup.connect(url).get() 一行搞定抓取+解析。// Jsoup 示例
Document doc = Jsoup.connect("https://example.com").timeout(5000).get();
String text = doc.text(); // 直接獲取純文本