2014-11-03 55 views
0

我有以下代碼:InputStream.close很慢,如果下載量是巨大的

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(); 

這是一個非常基本的程序,下載從URL數據。我的問題是,如果它完成下載所有的數據,它工作正常;但是,如果我試圖強行停止下載進度(例如打破while循環後1秒)的中途,

inputStream.close(); 

需要很長的時間來關閉InputStream。而它下載的數據越多,關閉它的時間就越多。

當我關閉inputStream時,會執行任何錯誤嗎?有沒有辦法關閉inputStream的安全性,不管在「inputStream」中剩下多少數據?

+0

你確定這與InputStream本身有關嗎?我無法在本地重現此行爲。 這可能與此有關嗎? 「重要提示:請注意,所有實體實現都必須確保在調用InputStream.close()方法後,所有分配的資源都可以正確解除分配。」 https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html#getContent%28%29 看看這裏,太:HTTP:// stackoverflow.com/questions/21818169/usage-of-consumecontent-of-httpentity 也許你應該調用EntityUtils.consume(HttpEntity)來代替? – 2014-11-03 20:41:16

+0

我試過EntityUtils.consume(HttpEntity)之前,並得到同樣的問題,因爲關閉inputStream – user3019299 2014-11-03 21:19:11

回答

0

我有同樣的問題,幫助我的是在結束InputStream之前和發行EntityUtils.consume(entity)之前發出httpget.abort()

httpget.reset()應該具有相同的效果。