`
terrencexu
  • 浏览: 121583 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HtmlParser EncodingChangeException: character mismatch

    博客分类:
  • Java
阅读更多

解析HTML,htmlparser是一个不错的选择,但是如果你初次使用,可能会不经意间遇到下面这个问题:

org.htmlparser.util.EncodingChangeException: character mismatch (new:  [0xfeff] != old:  [0xefï]) for encoding change from ISO-8859-1 to UTF-8 at character offset 0

 

这个问题的原因是服务器端返回的字符集是ISO-8859-1,但是在你解析的网页中却有下面这么一句话:

 

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>欢迎光临</title>
</head>

 

head中的charset=UTF-8与ISO-8859-1产生了冲突,所以就抛出了上述的异常。

 

对于这个问题网友已经给出了很多解决方案,包括修改htmlparser源代码等。

但是通过显式的为htmlparser设置字符集是可以解决这一问题的。

 

Parser parser = new Parser(url);
parser.setEncoding("UTF-8");
NodeList nodeList = parser.parse(new TagNameFilter("title"));
String title = nodeList.size() > 0  ? nodeList.elementAt(0).getFirstChild().getText() : null;

通过显式的设置encoding为UTF-8可以解决这一问题,即使在网页的head中charset是GBK或者gb2312等。

 

注:我没有完全测试过所有的情况,所以如果您遇到同类问题,使用该方式无法解决,请加comment,非常感谢

分享到:
评论
1 楼 qachenzude 2011-12-11  
buxing~~~

相关推荐

Global site tag (gtag.js) - Google Analytics