0

I need a method that determines the size of a file on the Internet. This is my method:

    private int getSize(String url){
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        //connection.setConnectTimeout(TIMEOUT);
        //connection.setReadTimeout(TIMEOUT);
        //connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        int size = connection.getContentLength();

        if(responseCode != 200){
            Log.e(LOG_TAG, "Fehlercode: " + responseCode + " beim Ermitteln der Dateigroesse von " + url);
            return -1;
        }

        return size;            
    } catch (IOException e) {
        Log.e(LOG_TAG, "Fehler beim Ermitteln der Dateigroesse von " + url, e);
        return -1;
    }
}

With Java (desktop) the method works - on Android it doesn't work. What's wrong with that?

Thanks for the help!

AxxG
  • 206
  • 3
  • 11

1 Answers1

2

HttpURLConnection and service interaction using the "gzip" compression(android2.2 and later) u should set:

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

reference api: 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: whenread() returns -1.

Yen
  • 51
  • 3