6

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问题中提到如何在下载文件之前知道文件的大小?

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

4

3 回答 3

9
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;

}
于 2016-07-30T11:09:15.697 回答
5

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

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

于 2016-02-11T06:22:07.740 回答
0
private final OkHttpClient client = new OkHttpClient();


public long run() throws Exception {
         Request request = new Request.Builder()
                 .url("http://server.com/file.mp3")
                 .build();

         Response response = client.newCall(request).execute();
        return  response.body().contentLength();
}
于 2016-06-26T21:56:55.817 回答