通过httpclient 下载指定url内容是出现重复内容

miliermili 2013-08-04 10:32:19
public void doRead() throws ClientProtocolException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://wenku.baidu.com/view/d6b2a9d2b14e852458fb5763.html");
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
InputStream in = null;
FileOutputStream out = null;
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
{
in = entity.getContent();
byte[] bytes = new byte[1024];
out = new FileOutputStream("E:/1/1.html");
//此处用于读取服务器响应的内容,问题也就在这儿,为什么从服务器下载的某个指定的网页中会有重复的内容,比如说某一行会重复一次
while(in.read(bytes)!=-1)
{
out.write(bytes,0,bytes.length);
out.flush();
}
out.close();
in.close();
httpGet.abort();
httpClient.getConnectionManager().shutdown();
}
}

利用httpclient爬去网页时,发现下载到的网页中会有很多重复的html代码,难道是因为 while(in.read(bytes)!=-1)
{
out.write(bytes,0,bytes.length);
out.flush();
}这个地方读取的有问题吗?后来发现采用EntityUtils.toByteArray(entity)的方法不会出项问题!但是菜鸟特变想知道上面的问题原因在哪里?
还有就是怎么控制编码的问题?
...全文
151 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
q1531 2013-08-06
  • 打赏
  • 举报
回复
while(in.read(bytes)!=-1) { out.write(bytes,0,bytes.length); out.flush(); } 这段代码有问题,改成 int len; while((len=in.read(bytes))!=-1) { out.write(bytes,0,len); out.flush(); } //原因是 read()返回是当前读入的字节数,不一定每次都会读满的 具体看api
miliermili 2013-08-04
  • 打赏
  • 举报
回复
求大神指教,
miliermili 2013-08-04
  • 打赏
  • 举报
回复
还有会出现很多null,难道是因为缓冲区的原因吗?
miliermili 2013-08-04
  • 打赏
  • 举报
回复
不知道为什么下载的页面同一段html会出现两次

25,980

社区成员

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

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