使用 Jsoup 爬取某站點(如新浪)返回 JSON 時拋出:
Exception in thread "main" org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml. Mimetype=application/json; charset=utf-8, URL=...
Jsoup 默認只接受 text/*、application/xml、application/xhtml+xml,遇到 application/json 直接拋異常。
在獲取 Connection 時調用 ignoreContentType(true):
public static String httpGet(String url, String cookie) throws IOException {
Connection con = Jsoup.connect(url).ignoreContentType(true); // 關鍵行
con.header("Accept", "text/html, application/xhtml+xml, */*");
con.header("Content-Type", "application/x-www-form-urlencoded");
con.header("User-Agent", "Mozilla/5.0 ...");
con.header("Cookie", cookie);
Document doc = con.get();
System.out.println(doc.title());
return doc.toString();
}
ignoreContentType(true) 告訴 Jsoup 跳過 MIME 類型校驗,直接解析響應體。適用於 API 返回 JSON/XML 等非標準 HTML 的場景。