androidurlconnection

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);
conection.connect();
int lenghtOfFile = conection.getContentLength();

If fileUrl is apk, lenghtOfFile always return -1.
But if it is image, video type,... lenghtOfFile return is exactly.

Why ?

I'm using eclipse, Android SDK revision 23.


Solution

  • 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.