網頁內容抓取是爬蟲開發、數據採集、API 整合等場景的基礎技能。本文提供完整的 Java 實現代碼,涵蓋基本 HTTP 請求、Proxy 代理配置、流式讀取優化等核心功能,代碼結構清晰,可直接整合至專案中使用。
封裝通用的獲取網頁內容方法,支援異常處理與資源自動釋放。使用 BufferedReader 逐行讀取並拼接,返回完整 HTML 字符串。
public static String getContent(String strUrl) {
try {
URL url = new URL(strUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
sb.append(s + "\r\n");
}
br.close();
return sb.toString();
} catch (Exception e) {
return "error open url:" + strUrl;
}
}
通過 Authenticator 實現帶認證的 HTTP 代理設置,配置系統屬性使後續連線自動走代理通道。適用於需要突破 IP 限制或隱藏真實 IP 的場景。
public static void initProxy(String host, int port, final String username, final String password) {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, new String(password).toCharArray());
}
});
System.setProperty("http.proxyType", "4");
System.setProperty("http.proxyPort", Integer.toString(port));
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxySet", "true");
}
主方法展示兩種讀取方式:一是配置 Proxy 後使用 HttpURLConnection 精細控制連線參數;二是直接調用封裝好的 getContent 方法。雙重驗證確保代理生效且內容正確獲取。
public static void main(String[] args) throws IOException {
String url = "https://www.jb51.net";
String proxy = "https://192.168.22.81";
int port = 80;
String username = "username";
String password = "password";
// 方式一:HttpURLConnection + Proxy
URL server = new URL(url);
initProxy(proxy, port, username, password);
HttpURLConnection connection = (HttpURLConnection) server.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String curLine = "";
String content = "";
while ((curLine = reader.readLine()) != null) {
content = content + curLine + "\r\n";
}
System.out.println("content= " + content);
is.close();
// 方式二:直接調用工具方法
System.out.println(getContent(url));
}
| 問題現象 | 可能原因 | 解決方案 |
|---|---|---|
| 返回亂碼 | 字符集不匹配 | 指定正確編碼 new InputStreamReader(is, "UTF-8") |
| 連線超時 | 代理不可用/目標限制 | 驗證代理有效性、設置合理超時、添加請求頭 |
| 403 Forbidden | 反爬蟲機制 | 完善請求頭、控制頻率、使用代理池輪換 IP |
| SSLHandshakeException | HTTPS 證書驗證失敗 | 導入證書或實現信任所有證書的 TrustManager |