Okhttp check file size without dowloading the file

[亡魂溺海] 提交于 2021-02-18 07:42:22

问题


The common examples for okhttp cover the scenarios of get and post.

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.

Currently I am using this code

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

mentioned in this stackoverflow question How to know the size of a file before downloading it?

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.


回答1:


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;

}



回答2:


I can't know for certain if this is possible in your case. But the general strategy is to first make an HTTP "HEAD" request to the server for that URL. This will not return the full content of the URL. Instead it will just return headers describing the URL. If the server knows the size of the content behind the URL, the Content-Length header will be set in the response. But the server may not know -- that's up to you to find out.

If the size is agreeable to the user, then you can perform a typical "GET" transaction for the URL, which will return the entire content in the body.




回答3:


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();
}


来源:https://stackoverflow.com/questions/35332016/okhttp-check-file-size-without-dowloading-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!