Okhttp check file size without dowloading the file

5.4k Views Asked by At

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.

5

There are 5 best solutions below

0
On

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.

0
On
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;

}
1
On
private final OkHttpClient client = new OkHttpClient();


public long run() throws Exception {
         Request request = new Request.Builder()
                 .url("http://server.com/file.mp3")
                 .build();

         Response response = client.newCall(request).execute();
        return  response.body().contentLength();
}
0
On

I tried Gil's answer but response.body().contentLength() was empty. So I use this response.header("content-length") instead:

    val client = OkHttpClient()
    val request = Request.Builder().url(url).head().build()
    val handler = Handler(Looper.getMainLooper())

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            // failed
        }

        override fun onResponse(call: Call, response: Response) {
            if (response.header("content-length") != null) {
                val size = response.header("content-length")!!.toLong()
                response.close()
            }
        }
    })
0
On

The previous answers didn't work for me. Getting the value from response.body().contentLength() never worked for me unless I actually downloaded the file, and I also found it was necessary to add the header to set "Accept-Encoding" to "identity" to avoid sometimes getting the length of the gzipped transfer rather than the actual length of the file.

Request request = new Request.Builder().url( url ).head()
    .addHeader("Accept-Encoding", "identity").build();

try {
    Response response = client.newCall( request ).execute();
    long contentLength =  Long.parseLong( response.header("Content-Length") );
    System.out.println( "FILE LENGTH: " + contentLength ); //*/
    response.close();

} catch( IOException e )
{
    System.out.println( "HTTP ERROR" + e.getMessage() );
}