---
title: "HtmlParser EncodingChangeException: character mismatch"
author: "terrencexu"
date: "2011-01-04T11:26:44Z"
tags: ["HTML"]
categories: ["编程语言"]
slug: "htmlparser-encodingchangeexception-character-mismatch"
draft: false
lastmod: "2011-01-04T11:27:58Z"
id: 858494
url: "https://terrencexu.iteye.com/blog/858494"
---

解析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，非常感谢