Okhttp check file size without dowloading the file
Asked Answered
A

5

7

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.

Assumpsit answered 11/2, 2016 at 6:9 Comment(0)
F
11
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;

}
Frerichs answered 30/7, 2016 at 11:9 Comment(0)
P
6

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.

Poser answered 11/2, 2016 at 6:22 Comment(0)
P
2

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()
            }
        }
    })
Plossl answered 2/11, 2022 at 7:26 Comment(0)
F
0
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();
}
Foetid answered 26/6, 2016 at 21:56 Comment(1)
this downloads the fileAssumpsit
T
0

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() );
}
Thermosetting answered 10/3, 2023 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.