1,确定目标。对于html页面来说,一般都有确定编码的语句:
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />
可以通过这一行的特征来取出网页的编码。
2,选出特征。
1)它是meta标签
2)具有http-equiv属性值为Content-Type
3)将属性content中的值取出,先采用“;”分拆取第二个元素,再采用“=”分拆取第二个元素
3,一切就绪,编码实现。通过目标的选取,以及特征的勾画,已经可以找到解决方法了,像上一篇htmlparser中filter使用实战中讲的类似,还是采用AndFilter、NodeFilter以及HasAttributeFilter实现,代码如下:
package org.algorithm;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
public class getEncoding {
//<meta http-equiv="Content-Type" content="text/html;charset=gb2312" /> //HTML编码
public static String getContentEncoding(String url) throws ParserException, IOException ,UnsupportedEncodingException{
String encoding = "";
try{
Parser parser = new Parser(url); //解析url链接
NodeFilter filter = new AndFilter(new TagNameFilter("meta"),new HasAttributeFilter("http-equiv","Content-Type"));//获取meta标签下的http-equiv属性
NodeList nodelist = parser.extractAllNodesThatMatch(filter);
if(nodelist != null){
TagNode list = (TagNode)nodelist.elementAt(0);
encoding = list.getAttribute("content").split(";")[1].trim();//将content的内容看成数组,使用split(";")[1]通过分号划分来获得数组中的第1个元素“charset=gb2312”,第0个元素是“text/html”
encoding = encoding.split("=")[1].trim();//仍然使用split()[]通过等于号来进行划分,获得数组中的第1个元素“gb2312”,第0个元素是“charset”
}
}catch(ParserException e){
e.printStackTrace();
}
return encoding;
}
public static void main(String[] args) throws ParserException, IOException, UnsupportedEncodingException {
String url="http://news.baidu.com/";
String encoding = getContentEncoding(url);
System.out.print(encoding);
}
}
Output:
gb2312