简体   繁体   English

如果下载大小很大,InputStream.close 会非常慢

[英]InputStream.close very slow if download size is huge

I have the following code:我有以下代码:

HttpGet downloadRequest = new HttpGet("url?size=10000000");
HttpResponse response = this.httpClient.execute(downloadRequest);
HttpEntity entity = response.getEntity();        
InputStream inputStream = entity.getContent();

while ((length = (int)inputStream.skip((long)BUFFER_SIZE)) != 0) {

 ...
}

inputStream.close();

It is a very basic program which downloads data from a url.这是一个非常基本的程序,它从一个 url 下载数据。 My question is that it is working fine if it finishes downloading all the data;我的问题是,如果它完成下载所有数据,它就可以正常工作; however, if I try to force to stop the download progress(eg break the while loop after 1 sec) midway,但是,如果我尝试在中途强制停止下载进度(例如,在 1 秒后中断 while 循环),

inputStream.close();

takes long time to close the inputStream.关闭 inputStream 需要很长时间。 And the more downloaded data it left, the more time it took to close it.它留下的下载数据越多,关闭它所需的时间就越长。

Does I do anything wrong when I close the inputStream?关闭 inputStream 时我做错了什么吗? Is there a way to close the inputStream right away safety which no matter how much data left in "inputStream"?无论“inputStream”中剩余多少数据,有没有办法立即安全地关闭inputStream?

I had the same problem and what helped me was to issue a httpget.abort() before closing the InputStream and before issuing EntityUtils.consume(entity) .我有同样的问题,是什么帮助我的是发出httpget.abort()关闭前InputStream和发行前EntityUtils.consume(entity)

httpget.reset() should have the same effect. httpget.reset()应该有同样的效果。

I had the same problem dealing with Post request.我在处理 Post 请求时遇到了同样的问题。 I traced into and found out what caused the HttpResponse hung was it is still streaming with large data.我追查并发现导致 HttpResponse 挂起的原因是它仍在传输大量数据。 The fix was to abort the request from the beginning.解决方法是从一开始就中止请求。 Something similar like following类似的东西如下

HttpPost httpPost = new HttpPost("request/endpoint");
httpPost.abort();
// do the rest down here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM