webmagic icon indicating copy to clipboard operation
webmagic copied to clipboard

Enhance auto charset detect/加强编码检测

Open code4craft opened this issue 12 years ago • 2 comments

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 .

code4craft avatar May 14 '14 15:05 code4craft

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)

sebastien-ma avatar May 23 '14 08:05 sebastien-ma

多谢 @sebastian1118 ,已经按照这个方式进行修复。 考虑到测试的问题,引入了moco作为server的测试。

code4craft avatar May 26 '14 09:05 code4craft