Reputation: 628
I am working on Android application where I download the files from the server using below code: Code:
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();
Sometimes, the code is generating following exception.
Error stack trace:
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)
I read about this issue on the forums and understood that this issue is caused when content length mentioned in the request header is not matching with the response size.
How can I avoid this exception?
I would appreciate any suggestions and thoughts on this topic. Thank you.
Upvotes: 2
Views: 2459