URLConnection getContentLength() is returning a negative value

By default, this implementation of HttpURLConnection requests that servers use gzip compression.
Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream().

Instead, read that stream until it is exhausted: when read() returns -1.

Gzip compression can be disabled by setting the acceptable encodings in the request header:

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

So try this:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity"); // <--- Add this line
int length = connection.getContentLength(); // i get negetive length

Source (Performance paragraph): http://developer.android.com/reference/java/net/HttpURLConnection.html

Leave a Comment