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

pt1*_*123 4 android http-content-length okhttp

okhttp 的常见示例涵盖了 get 和 post 的场景。

但我需要通过 url 获取文件的文件大小。由于我需要通知用户,并且只有在获得他们的批准后才能下载文件。

目前我正在使用此代码

URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
Run Code Online (Sandbox Code Playgroud)

在这个 stackoverflow 问题中提到如何在下载文件之前知道文件的大小?

哪个有效,但是当我在我的项目中使用 okhttp 来处理其他 get 请求时,我也希望将它用于这种情况。

Gil*_* SH 8

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;

}
Run Code Online (Sandbox Code Playgroud)


Dou*_*son 6

我无法确定这对于您的情况是否可行。但一般策略是首先向服务器发出该 URL 的 HTTP“HEAD”请求。这不会返回 URL 的完整内容。相反,它只会返回描述 URL 的标头。如果服务器知道 URL 后面内容的大小,则将在响应中设置 Content-Length 标头。但服务器可能不知道——这取决于你来找出答案。

如果用户同意大小,那么您可以对 URL 执行典型的“GET”事务,这将返回正文中的全部内容。