Enhance auto charset detect/加强编码检测
In WebMagic 0.5.1 and below, it use http header "Content-Type" for charset detection. But there is some site without this header.
Try to use charset in meta for detection.
protected String getHtmlCharset(CloseableHttpResponse httpResponse) throws IOException {
// 1、encoding in http header Content-Type
String value = httpResponse.getEntity().getContentType().getValue();
String charset = UrlUtils.getCharset(value);
if (StringUtils.isEmpty(charset)) {
// 2、charset in meta
String content = IOUtils.toString(httpResponse.getEntity().getContent());
if (StringUtils.isNotEmpty(content)) {
Document document = Jsoup.parse(content);
Elements links = document.select("meta");
for (Element link : links) {
// 2.1、 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
String metaContent = link.attr("content");
String metaCharset = link.attr("charset");
if (metaContent.indexOf("charset") != -1) {
metaContent = metaContent.substring(metaContent.indexOf("charset"), metaContent.length());
charset = metaContent.split("=")[1];
break;
}
// 2.2、 <meta charset="UTF-8" />
else if (StringUtils.isNotEmpty(metaCharset)) {
charset = metaCharset;
break;
}
}
// 3、todo use tools as cpdetector for content decode
}
}
return charset;
}
Thanks to @fengwuze .
IOUtils.toString(httpResponse.getEntity().getContent()) 会使用并关闭response的inputstram 当下一个方法使用检测到的charset编码时会报 java.io.IOException: Attempted read from closed stream.
建议先吧content取到byte[]而不是string里 因为用错误的charset出来的string无法转回正确的charset了。 byte[] contentByteArray = IOUtils.toByteArray(httpResponse.getEntity().getContent());
取到正确的charset之后通过byte[]创建正确的string new String(contentByteArray, charset)
多谢 @sebastian1118 ,已经按照这个方式进行修复。 考虑到测试的问题,引入了moco作为server的测试。