|
html网页的内容大致如下:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type;charset=gb2312" />
- <title>CSDN首页 </title>
- ...
- </head>
- <body>
- .....
- </html>
我使用以下语句抓取类似上面的网页:
- URL url = new URL("http://www.csdn.net");
- HttpURLConnection connection = (HttpURLConnection)url.openConnection();
-
- String contentType = connection.getHeaderField("Content-Type");
- contentType = connection.getContentType();
无论是哪一句,得到的contentType的值都是text/html,而不包含后面的charset=gb2312,这是为什么?
我注意到一个问题,content="text/html; charset=gb2312"这里,在;和charset之间有一个空格,是否因为这个空格的缘故,而不能得到content-type的准确值 还有没有其他的办法可以得到页面的编码字符集?
回答: connection.getContentType(); 这个需要服务器设置了 ContentType才可以,这个数据在文件头里面,而不是在文件的主体(也就是你看到的html)里面。 所以检测页面类型需要分3步,如果这一步不行,则用下一个 1 看header里面的ContentType,也就是你用的那个方法 2 看 html 里面的 ContentType ,也就是解析html页面 3 对html数据进行自动评估,类似于it里面的自动检测编码类型。
一段典型的返回信息的Header数据 HTTP/1.1 200 OK Date: Mon, 01 Sep 2008 23:13:31 GMT Server: Apache/2.2.4 (Win32) mod_jk/1.2.26 Vary: Host,Accept-Encoding Set-Cookie: JAVA2000_STYLE_ID=1; Domain=www.java2000.net; Expires=Thu, 03-Nov-2011 09:00:10 GMT; Path=/ Content-Encoding: gzip Transfer-Encoding: chunked Content-Type: text/html;charset=UTF-8
<html> 。。。。从这里开始是数据的本体
|
|