2

我正在使用以下代码从服务器下载文件的 Android 应用程序: 代码:

    myURLConnection = (HttpURLConnection) myURL.openConnection();
    myURLConnection.setUseCaches(false);
    myURLConnection.setDoInput(true);


     int status = myURLConnection.getResponseCode();
     BufferedInputStream is = new BufferedInputStream(myURLConnection.getInputStream());
     FileOutputStream result = new FileOutputStream(app_context.getFilesDir() + ""+a.getKey(), true);
     byte[] buffer = new byte[1024];
     int length;

    while ((length = is.read(buffer)) != -1) {
          result.write(buffer, 0, length);
      }

     result.flush();
     result.close();
     is.close();

有时,代码会生成以下异常。

错误堆栈跟踪:

java.net.ProtocolException: unexpected end of stream
    at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:449)
    at com.android.okio.RealBufferedSource$1.read(RealBufferedSource.java:168)
    at java.io.InputStream.read(InputStream.java:162)
    at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:149)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:295)
    at java.io.InputStream.read(InputStream.java:162)

我在论坛上阅读了有关此问题的信息,并了解此问题是由于请求标头中提到的内容长度与响应大小不匹配引起的。

我怎样才能避免这个异常?

我将不胜感激有关此主题的任何建议和想法。谢谢你。

4

0 回答 0