Android Getcontentlength Always Return -1 When Downloading Apk File
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 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.
Post a Comment for "Android Getcontentlength Always Return -1 When Downloading Apk File"