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.
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.
The file size is available in the HTTP Content-Length response header.
Note that starting from Android 4.4, the networking layer (so also the HttpUrlConnection APIs) is implemented through OkHttp.
OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With