如果Content Length 在頭文件中沒有描述
暫時還沒有解決方案
如果Content Long在頭文件中有描述
方案一:
偽裝成瀏覽器
1
|
conn.setRequestProperty("User-Agent", " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); |
代碼中加入代理
1
2
3
4
5
6
7
8
|
String host = "127.0.0.1" ; String port = "8888" ; setProxy(host, port); public static void setProxy(String host, String port) { System.setProperty( "proxySet" , "true" ); System.setProperty( "proxyHost" , host); System.setProperty( "proxyPort" , port); } |
方案二:
加入以下屬性,讓服務(wù)器不要gzip方式壓縮:
Java Doc 有對此的描述:
1
2
3
|
By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream(). Instead, read that stream until it is exhausted: whenread() returns -1. conn.setRequestProperty("Accept-Encoding", "identity"); |
以上這篇基于java下載中g(shù)etContentLength()一直為-1的一些思路就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。