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

Java 實現網頁爬蟲抓取內容的兩種方式

     編輯:Java 相關知識

Java 抓取網頁內容常見兩種路徑:使用 Apache HttpClient(功能豐富、自動處理 Cookie/重定向)或 JDK 原生 HttpURLConnection(零依賴、輕量)。本文提供兩種完整可用示例,並處理編碼與 HTML 標簽清洗。

方式一:Apache HttpClient(推薦生產環境)

需引入依賴: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("<[^>]*>", "");
    }
}

方式二:JDK 原生 HttpURLConnection(零依賴)

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("<[^>]*>", "");
    }
}

關鍵點對比

特性HttpClientHttpURLConnection
依賴需外部 JAR零依賴
Cookie 管理自動手動
重定向自動自動(可關閉)
連接池內建無
代理支援完善需手動設置
適用場景複雜爬蟲、生產系統簡單抓取、受限環境

編碼處理最佳實踐

  1. 優先從 Content-Type Header 獲取 charset。
  2. 若無 Header,嘗試從 HTML <meta charset=...> 解析。
  3. 最終 fallback 到 UTF-8 或目標站點常用編碼(如 GB2312/GBK)。
  4. 使用 new String(bytes, detectedCharset) 解碼,切勿硬編碼 ISO-8859-1 中轉(除非確定)。

現代替代方案(推薦)

新項目建議使用 OkHttp 或 Jsoup:

  • OkHttp:高性能 HTTP 客戶端,支援 HTTP/2、連接池、自動重試。
  • Jsoup:專為 HTML 解析設計,Jsoup.connect(url).get() 一行搞定抓取+解析。
// Jsoup 示例
Document doc = Jsoup.connect("https://example.com").timeout(5000).get();
String text = doc.text(); // 直接獲取純文本
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved