Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okhttp check file size without dowloading the file

The common examples for okhttp cover the scenarios of get and post.

But I need to get the file size of a file with a url. Since I need to inform the the user, and only after getting their approval to download the file.

Currently I am using this code

URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();

mentioned in this stackoverflow question How to know the size of a file before downloading it?

Which works but as I am using okhttp in my project for other get requests I was hoping to use it for this scenario also.

like image 295
pt123 Avatar asked Feb 11 '16 06:02

pt123


People also ask

How do I know the size of a file before downloading?

you can get a header called Content-Length form the HTTP Response object that you get, this will give you the length of the file. you should note though, that some servers don't return that information, and the only way to know the actual size is to read everything from the response.

Which HTTP method can request the size of a file before it is downloaded?

The file size is available in the HTTP Content-Length response header.

Does OkHttp use HttpUrlConnection?

Note that starting from Android 4.4, the networking layer (so also the HttpUrlConnection APIs) is implemented through OkHttp.

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.


2 Answers

public static long getRemoteFileSize(String url) {
    OkHttpClient client = new OkHttpClient();
    // get only the head not the whole file
    Request request = new Request.Builder().url(url).head().build();
    Response response=null;
    try {
        response = client.newCall(request).execute();
        // OKHTTP put the length from the header here even though the body is empty 
        long size = response.body().contentLength();
        response.close();
        return  size;
    } catch (IOException e) {
        if (response!=null) {
            response.close();

        }
        e.printStackTrace();
    }
    return 0;

}
like image 134
Gil SH Avatar answered Sep 28 '22 09:09

Gil SH


I can't know for certain if this is possible in your case. But the general strategy is to first make an HTTP "HEAD" request to the server for that URL. This will not return the full content of the URL. Instead it will just return headers describing the URL. If the server knows the size of the content behind the URL, the Content-Length header will be set in the response. But the server may not know -- that's up to you to find out.

If the size is agreeable to the user, then you can perform a typical "GET" transaction for the URL, which will return the entire content in the body.

like image 23
Doug Stevenson Avatar answered Sep 28 '22 09:09

Doug Stevenson