android - Okhttp 在不下载文件的情况下检查文件大小

标签 android okhttp http-content-length

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/

相关文章:

c# - ASP.NET Web Api - 使用分块传输编码时,框架不会将 JSON 转换为对象

java - 安卓服务停止

android - 按下时如何更改自定义键盘颜色...!

java - 改造 "java.net.ProtocolException: Unexpected status line",有人吗?

java - 无法通过代理连接到 websocket

java - 如何用okhttp关闭HTTP连接?

python - 谷歌应用引擎: Response "Content-Length" header is always 0

android - 在 Android 4.2 中,当使用 intent 以编程方式安装 APK 时,如何允许降级?

java - 如何在观察者模式中检查 JsonArray 中 JsonObject 的值?

node.js - 如何使用 fetch 使用 multipart/form-data header 和 FormData 进行 POST