java下载网页源码,content type有问题?(初学,求教)

chen_q07 2012-05-09 11:35:48

0

踩 按照书上例子写了个GetPageSource的代码,运行结果如下

chenqi@chenqi-laptop ~/MyPro/Java/NetWork $ java GetPageSource http://www.baidu.com/
Date: Wed May 09 00:29:07 CST 2012
Content-Type: text/html;charset=gb2312

但是,我用firefox查看该页源码,发现是这样的:

<meta http-equiv=Content-Type content="text/html;charset=utf-8">

两个内容的charset不一致。。。。有点小无语。不知道为什么。

以下附上源码,求高手分析下:)


import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

class GetPageSource {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: GetPageSource URL");
return;
}

String strURL = args[0];
URL url = null;
try {
url = new URL(strURL);
} catch (MalformedURLException e) {
System.err.println("Invalid format of URL:" + url + "," + e.getMessage());
return;
}

URLConnection urlCon = null;
try {
urlCon = url.openConnection();
} catch (IOException e) {
System.err.println("Can't get connection from URL: " + e.getMessage());
}
// print properties of this url
System.out.println("Date: " + new Date(urlCon.getDate()));
System.out.println("Content-Type: " + urlCon.getContentType());
System.out.println("Expires: " + urlCon.getExpiration());
System.out.println("Last-Modified: " + new Date(urlCon.getLastModified()));
System.out.println("Content-Length: " + urlCon.getContentLength());

// download page source from this url
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = urlCon.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
int count = 0;
String tmp = null;
while ( (tmp = reader.readLine()) != null ) {
System.out.println(tmp);
count += tmp.length();
}
System.out.println("Count = " + count);
} catch (IOException e) {
System.err.println("I/O failed: " + e.getMessage());
} finally {
try {
if (reader != null) reader.close();
} catch (IOException e) { }
}
}
}
...全文
116 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧