How to calculate the file size from the URL in Java

I'm trying to get a bunch of PDF links from web services. I want to give users the file size of each link

Is there any way to complete the task?

thank you

Solution

Using the head request, you can do the following:

private int getFileSize(URL url) {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
        conn.getInputStream();
        return conn.getContentLength();
    } catch (IOException e) {
        return -1;
    } finally {
        conn.disconnect();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>