在網頁抓取與爬蟲開發中,正確識別頁面編碼是解析內容的前提。Java 標準庫無現成 API,需綜合多種策略。本文提供一個生產級工具類,按優先級實現三重檢測機制。
Content-Type 中的 charset 參數,最權威、開銷最小。<meta charset=...> 或 http-equiv,覆蓋無 Header 情況。cpdetector 庫(整合 JChardet、ASCII 檢測等),對原始字節流進行統計推斷。public class WebEncoding {
private static final CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
static {
detector.add(new HTMLCodepageDetector(false));
detector.add(JChardetFacade.getInstance());
}
public String getCharset(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 1. HTTP Header
String encoding = extractFromHeader(conn);
if (encoding != null) return encoding;
// 2. Meta 標籤
String htmlPrefix = downloadPrefix(url, 1024);
encoding = extractFromMeta(htmlPrefix);
if (encoding != null) return encoding;
// 3. 字節分析
encoding = detector.detectCodepage(url)?.name();
return encoding != null ? encoding : "GBK"; // 中文站默認兜底
}
// 輔助方法省略...
}
<dependency>
<groupId>info.monitorenter</groupId>
<artifactId>cpdetector</artifactId>
<version>1.0.12</version>
</dependency>
「Header → Meta → 統計」三級降級策略兼顧準確性與魯棒性,配合 cpdetector 成熟庫,可滿足 99%+ 爬蟲場景的編碼識別需求。源碼已整理為可直接集成的工具類。