Anshuman Pattnaik
Anshuman Pattnaik

Reputation: 923

Android getContentLength return -1 but in browser returns the file size , how?

I am trying find the file size from an URL using Android but i am getting getContentLength() : -1 , but if i will open the url in any browser then the browser can able to calculate the file size , where as browser is also a client side application.

MyCode :

 try {
        URL url = new URL("https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode()
                    + " " + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        //fileLength  : -1;  

    } catch (Exception e) {
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }

This is my above android code , i am getting -1 as the file length but the same URL file size can easily calculated by the browser.

Please suggest me some solution.

Upvotes: 0

Views: 441

Answers (2)

gonga dev
gonga dev

Reputation: 117

Try to change the link from

"https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0" 

To

"https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=1"

Upvotes: 1

CodeX
CodeX

Reputation: 156

This code works fine for me:

public int getFileSizeFromURL(String urlPath) {
    int fileSize = 0;
    try {
        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection)     url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        fileSize = connection.getContentLength();
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileSize;
}

code based on this answer

Upvotes: 1

Related Questions