JAVA读取网页内容串行的问题

fatiezhe fatiezhe 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
首先代码如下:
Spider类

public class Spider implements Runnable{

HttpURLConnection huc;
InputStream is;
BufferedReader reader;
String url;

public Spider(String str){
try {
url=str;
} catch (Exception e) {
e.printStackTrace();
}
try {
huc=(HttpURLConnection)new URL(url).openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

new Thread(this).start();
}

public void run() {
try {
huc.setRequestMethod("GET");
huc.setRequestProperty("user-agent","mozilla/4.0 (compatible; msie 6.0; windows 2000)");
} catch (ProtocolException e) {
e.printStackTrace();
}
try {
huc.setUseCaches(true);
huc.connect();

} catch (IOException e) {
e.printStackTrace();
}
try {
is=huc.getInputStream();
reader=new BufferedReader(new InputStreamReader(is,huc.getContentType().equals("text-html; charset=gb2312")?"gb2312":"UTF-8"));
String str;
System.out.flush();
while((str=reader.readLine())!=null){
System.out.println(str);
System.out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
is.close();
huc.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
}


结果在输出的结果与右键点浏览器查看源码的结果比较发现:
输出的结果如下:
<html>
<title>XXXXXXXXXXXXX</title>
</head>
<body >

<head>

原本应该在第二行的<head>跑到了后面,发生了串行的现象,不只为何,而且串行的位置也不固定,也就是说每次运行得到的结果都不一致,求高人解答
...全文
评论 33
收藏 已收藏
分享
返回顶部
fatiezhe
Web 开发 81,107 成员 341,720 内容