okhttp常见的例子涵盖了get和post的场景。
但我需要通过 url 获取文件的文件大小。由于我需要通知用户,只有在获得他们的同意后才能下载文件。
目前我正在使用这段代码
URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
在此stackoverflow问题中提到How to know the size of a file before downloading it?
这行得通,但因为我在我的项目中使用 okhttp 来处理其他获取请求,所以我希望也将它用于这种情况。
最佳答案
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;
}
关于android - Okhttp 在不下载文件的情况下检查文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332016/