獲取遠(yuǎn)程文件大小 網(wǎng)上給的方案大部分是下面這條,但是會(huì)出現(xiàn)getContentLength()為-1的情況送丰,搜索結(jié)果大部分為
conn.setRequestProperty("Accept-Encoding", "identity");
這條建議,但無(wú)效果
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;