InputStream will not close or is required forever

I am trying to load an external mp3 into internal memory. However, the files I'm trying to download are large, so I'm trying to load them into 1 MB chunks so you can start playing them while the rest is loading. Here is my stream code:

InputStream is = null; OutputStream os = null; try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet( url ); HttpResponse response = client.execute( get ); MyLog.d( "Connection established" ); byte[] buffer = new byte[8192]; is = new BufferedInputStream( response.getEntity().getContent(), buffer.length ); os = openFileOutput( filename, MODE_PRIVATE ); int size; int totalSize = 0; while (( size = is.read( buffer ) ) != -1 && totalSize < 1048576) { os.write( buffer, 0, size ); totalSize += size; } MyLog.d( "Finished downloading mix - " + totalSize + " bytes" ); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if ( os != null ) { try { os.flush(); os.close(); } catch (IOException e) { MyLog.e( "Failed to close output stream." ); } } if ( is != null ) { try { is.close(); } catch (IOException e) { MyLog.e( "Failed to close input stream." ); } } } 

It loads the file in order, but when it gets to is.close () in the finally declaration, it hangs. If I wait a very long time, it will be finally closed. It looks like it is still loading the rest of the file. How can I avoid this and close the stream immediately?

+6
source share
1 answer

With HTTP, you usually still need to read (and throw away) the rest of the response stream - you can't just close it. All flow should be consumed. I'm not sure Android httpclient is based on commons httpclient 3 or 4 - with 4 you can use HttpUriRequest # abort () to finish earlier. Not sure 3 has such an option

Edit: Viewed and looks like httpclient 3, and you can do httpget.abort ()

+7
source

Source: https://habr.com/ru/post/886593/


All Articles