Okhttp检查文件大小而不下载文件 [英] Okhttp check file size without dowloading the file
本文介绍了Okhttp检查文件大小而不下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
okhttp的常见示例涵盖了get和post的场景.
The common examples for okhttp cover the scenarios of get and post.
但是我需要获取带有url的文件的文件大小.由于我需要通知用户,只有在获得他们的批准后才能下载文件.
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.
当前我正在使用此代码
URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
在此stackoverflow问题中提到如何在下载文件之前知道文件的大小吗?
mentioned in this stackoverflow question How to know the size of a file before downloading it?
这是可行的,但是当我在项目中使用okhttp进行其他get请求时,我也希望在这种情况下使用它.
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.
推荐答案
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;
}
这篇关于Okhttp检查文件大小而不下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文