Skip to content Skip to sidebar Skip to footer

Android Getcontentlength Always Return -1 When Downloading Apk File

I'm using the following code for downloading file in my Android project: URL url = new URL(fileUrl); URLConnection conection= url.openConnection(); conection.setDoOutput(true); con

Solution 1:

The content length is not always available because by default Android request a GZIP compressed response. Source: Android documentation.

Quoting the link:

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header:

urlConnection.setRequestProperty("Accept-Encoding", "identity");

Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response.

getContentLength() returns the number of bytes transmitted and cannot be used to predict how many bytes can be read from getInputStream() for compressed streams. Instead, read that stream until it is exhausted, i.e. when read() returns -1.

Whether or not the response then actually is compressed depends on the server of course.

Post a Comment for "Android Getcontentlength Always Return -1 When Downloading Apk File"