如何从Java中的URL计算文件大小
问题内容:
我试图从Web服务中获取大量pdf链接,但我想为用户提供每个链接的文件大小。
有没有办法完成这项任务?
谢谢
问题答案:
使用HEAD请求,您可以执行以下操作:
private static int getFileSize(URL url) {
URLConnection conn = null;
try {
conn = url.openConnection();
if(conn instanceof HttpURLConnection) {
((HttpURLConnection)conn).setRequestMethod("HEAD");
}
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(conn instanceof HttpURLConnection) {
((HttpURLConnection)conn).disconnect();
}
}
}