java 通过url获取文件大小

来源:互联网 发布:点明读屏软件 编辑:程序博客网 时间:2024/06/05 10:53

1:目的 :在不下载文件的前提下,通过http head 请求,获取一个文件的大小;


2:具体代码方法如下:


/**    * 获取网络文件大小     */    private static long getFileLength(String downloadUrl) throws IOException{  if(downloadUrl == null || "".equals(downloadUrl)){  return 0L ;   }      URL url = new URL(downloadUrl);      HttpURLConnection conn = null;      try {          conn = (HttpURLConnection) url.openConnection();          conn.setRequestMethod("HEAD");          conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");          return (long) conn.getContentLength();      } catch (IOException e) {          return 0L;      } finally {          conn.disconnect();    }     }


原创粉丝点击