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.
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 ofgetInputStream()
. TheContent-Encoding
andContent-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 theContent-Encoding
header of the response.
getContentLength()
returns the number of bytes transmitted and cannot be used to predict how many bytes can be read fromgetInputStream()
for compressed streams. Instead, read that stream until it is exhausted, i.e. whenread()
returns-1
.
Whether or not the response then actually is compressed depends on the server of course.