首頁  >  文章  >  Java  >  JAVA下載中getContentLength()一直為-1的一些思路

JAVA下載中getContentLength()一直為-1的一些思路

巴扎黑
巴扎黑原創
2017-06-26 10:21:241803瀏覽
如果Content Length 在頭檔中沒有描述

暫時還沒有解決方案

如果Content Long在頭檔中有描述

 


方案一:

 偽裝成瀏覽器

 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");

 程式碼中加入代理程式

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);    
}

 

 

方案二:

加入下列屬性,讓伺服器不要gzip方式壓縮:

# Java Doc 有對此的描述:

By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength()#o returns the# 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下載中getContentLength()一直為-1的一些思路的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn