【问题标题】:How to detect if network connection is down while downloading file using InputStream and FileOutputStream in android?如何在android中使用InputStream和FileOutputStream下载文件时检测网络连接是否断开?
【发布时间】:2015-04-13 09:09:47
【问题描述】:

我正在下载一个文件,然后使用以下代码将其写入 sdcard:

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

一切正常。通常下载文件需要 2 分钟。如果我在下载过程中取出网线,那么它似乎永远停留在 while 循环中。该代码在 try catch 块中,但我没有得到任何异常。拔下网络电缆时,无论如何要摆脱那个while循环。提前致谢。

【问题讨论】:

  • 如果你添加一个&& isConnectedToInternet() 方法,你将在循环中实现?

标签: android inputstream httpresponse fileoutputstream httpentity


【解决方案1】:

您应该能够通过在HttpClient 上设置超时来解决此问题 - 套接字保持打开状态以防服务器响应延迟。你可以简单地告诉它不要等那么久。在此处查看超时选项:

How to set HttpResponse timeout for Android in Java

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多