HttpURLConnection 得到编码格式
HttpURLConnection 取百度首页
URLConnection urlc = new URL("http://www.baidu.com/") .openConnection();
System.out.println(urlc.getContentType()); InputStream is = urlc.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(is,"gbk"));
getContentType() 值为:text/html;charset=gb2312。
同样取 http://www.126.com 页面 ,getContentType() 只能取到text/html 。查看126 源文件中:<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 发现 text/html;后多了一个空格 就不能取到Content-Type的值。
在网上搜了下资料 找到了2中方法:
1. 用 utf-8 和 gbk 各转化一次页面内容得出字符数 ,谁大 就取那种编码 。只是一种方法,其他编码不提
2. 用正则表达式 匹配<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> ,同样取得charset ,再次对页面进行转码
如有更好方法 请大家指出。