获取远程文件大小 网上给的方案大部分是下面这条,但是会出现getContentLength()为-1的情况,搜索结果大部分为
conn.setRequestProperty("Accept-Encoding", "identity");
这条建议,但无效果
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestProperty("Accept-Encoding", "identity");
long contentLength = conn.getContentLength();
conn.disconnect();
return contentLength;
看一下源码恍然大悟
看一下下面两段代码就知道了
public int getContentLength() {
long l = getContentLengthLong();
if (l > Integer.MAX_VALUE)
return -1;
return (int) l;
}
public long getContentLengthLong() {
return getHeaderFieldLong("content-length", -1);
}
返回Long就可以了
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestProperty("Accept-Encoding", "identity");
long contentLength = conn.getContentLengthLong();
conn.disconnect();
return contentLength;