androidinputstreamhttpresponsefileoutputstreamhttpentity

How to detect if network connection is down while downloading file using InputStream and FileOutputStream in android?


I am downloading a file and then writing it into sdcard using following code:

 HttpResponse response = httpClient.execute(request);
 HttpEntity entity = response.getEntity();
 InputStream is = entity.getContent();
 File file = new File(Environment.getExternalStorageDirectory()+"/MyProject/data");
 FileOutputStream fos = new FileOutputStream(file);
 int inByte;
 while((inByte = is.read()) != -1){ 
     fos.write(inByte);
     System.out.println("in while loop inByte: "+inByte);
 }
 fos.close();
 is.close();

Everything is working fine. Normally it takes 2 minutes to download file. If i take out network cable during downloading then seems like it stays in while loop forever. That code is in try catch block but i do not get any exception. Is there anyway to get out of that while loop when network cable is unplugged. Thanks in advance.


Solution

  • You should be able to solve this by setting the timeouts on the HttpClient - the socket is staying open in case the server has a delay in the response. You can simply tell it to not wait so long. See the timeout options here:

    How to set HttpResponse timeout for Android in Java