我正在使用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)
我在论坛上阅读了这个问题,并了解到当请求标题中提到的内容长度与响应大小不匹配时会导致此问题。
如何避免此异常?
我很感激有关此主题的任何建议和想法。谢谢。