zoukankan      html  css  js  c++  java
  • 我的知识库(4) java获取页面编码(Z)

    文章出自:http://babyjoycry.javaeye.com/blog/587527 在此感谢原作者...\(^o^)/~

    最近研究抓取网页内容,发现要获取页面的编码格式,Java没有现成的实现方法,虽然csdn上有个达人写了一篇文章,附有代码,可惜,我没有找到相关的包,不得已,只好自己动手丰衣足食了。

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;

    import cpdetector.io.CodepageDetectorProxy;
    import cpdetector.io.HTMLCodepageDetector;
    import cpdetector.io.JChardetFacade;

    public class PageEncodeDetector {
    private static CodepageDetectorProxy detector = CodepageDetectorProxy
    .getInstance();

    static {
    detector.add(new HTMLCodepageDetector(false));
    detector.add(JChardetFacade.getInstance());
    }

    /**
    * 测试用例
    *
    * @param args
    */

    public static void main(String[] args) {
    PageEncodeDetector web = new PageEncodeDetector();
    try {
    System.out.println(web.getCharset("http://www.baidu.com/"));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    /**
    * @param strurl
    * 页面url地址,需要以 http://开始,例:http://www.pujia.com
    * @return
    * @throws IOException
    */

    public String getCharset(String strurl) throws IOException {
    // 定义URL对象
    URL url = new URL(strurl);
    // 获取http连接对象
    HttpURLConnection urlConnection = (HttpURLConnection) url
    .openConnection();
    ;
    urlConnection.connect();
    // 网页编码
    String strencoding = null;

    /**
    * 首先根据header信息,判断页面编码
    */

    // map存放的是header信息(url页面的头信息)
    Map<String, List<String>> map = urlConnection.getHeaderFields();
    Set<String> keys = map.keySet();
    Iterator<String> iterator = keys.iterator();

    // 遍历,查找字符编码
    String key = null;
    String tmp = null;
    while (iterator.hasNext()) {
    key = iterator.next();
    tmp = map.get(ke
  • 相关阅读:
    clear:both其实是有瑕疵的
    CSS3不遥远,几个特性你要知道
    JavaScript使用数组拼接字符串性能如何?
    CSS网页宽度怎么定比较合适
    浅析JavaScript的垃圾回收机制
    淡入淡出效果的js原生实现
    非阻塞式JavaScript脚本及延伸知识
    HTML5 Canvas圣诞树
    Ubuntu查看和自动挂载硬盘
    正则表达式批量重命名
  • 原文地址:https://www.cnblogs.com/chero/p/2465254.html
Copyright © 2011-2022 走看看