我遇到了以下問題:當通過代理使用URLConnection
時,內容長度始終設置爲-1
。URLConnection無法通過代理正確處理內容長度
首先我檢查了代理真的返回Content-Length
(lynx
和wget
通過代理也在努力;沒有別的路可走互聯網從本地網絡):我寫
$ lynx -source -head ftp://ftp.wipo.int/pub/published_pct_sequences/publication/2003/1218/WO03_104476/WO2003-104476-001.zip
HTTP/1.1 200 OK
Last-Modified: Mon, 09 Jul 2007 17:02:37 GMT
Content-Type: application/x-zip-compressed
Content-Length: 30745
Connection: close
Date: Thu, 02 Feb 2012 17:18:52 GMT
$ wget -S -X HEAD ftp://ftp.wipo.int/pub/published_pct_sequences/publication/2003/1218/WO03_104476/WO2003-104476-001.zip
--2012-04-03 19:36:54-- ftp://ftp.wipo.int/pub/published_pct_sequences/publication/2003/1218/WO03_104476/WO2003-104476-001.zip
Resolving proxy... 10.10.0.12
Connecting to proxy|10.10.0.12|:8080... connected.
Proxy request sent, awaiting response...
HTTP/1.1 200 OK
Last-Modified: Mon, 09 Jul 2007 17:02:37 GMT
Content-Type: application/x-zip-compressed
Content-Length: 30745
Connection: close
Age: 0
Date: Tue, 03 Apr 2012 17:36:54 GMT
Length: 30745 (30K) [application/x-zip-compressed]
Saving to: `WO2003-104476-001.zip'
在Java:
URL url = new URL("ftp://ftp.wipo.int/pub/published_pct_sequences/publication/2003/1218/WO03_104476/WO2003-104476-001.zip");
int length = url.openConnection().getContentLength();
logger.debug("Got length: " + length);
和我得到-1
。我開始調試FtpURLConnection
和事實證明,必要的信息是HttpURLConnection.responses
場但它永遠不會正確地從那裏居住底層:
(有在頭Content-Length: 30745
)。內容長度在您開始讀取流或甚至在讀取流之後不會更新。代碼:
URL url = new URL("ftp://ftp.wipo.int/pub/published_pct_sequences/publication/2003/1218/WO03_104476/WO2003-104476-001.zip");
URLConnection connection = url.openConnection();
logger.debug("Got length (1): " + connection.getContentLength());
InputStream input = connection.getInputStream();
byte[] buffer = new byte[4096];
int count = 0, len;
while ((len = input.read(buffer)) > 0) {
count += len;
}
logger.debug("Got length (2): " + connection.getContentLength() + " but wanted " + count);
輸出:
Got length (1): -1
Got length (2): -1 but wanted 30745
現在看來似乎是在JDK6中的錯誤,所以我已經打開了新的bug#7168608。
- 如果有人可以幫我寫代碼應該返回正確的內容長度直接FTP連接,FTP連接通過代理和本地
file:/
網址,我將不勝感激。 - 如果給出的問題不能用JDK6解決,建議任何其他庫肯定適用於我提到的所有情況(Apache Http Client?)。
爲什麼你需要的內容長度?數據的實際流是否正確?如果是這樣,你不需要內容的長度,一切工作正常。 – jtahlborn 2012-04-03 14:08:37
@jtahlborn:實際的URL是正確的(它是公共FTP,所以你可以測試)。我需要了解內容長度**,而不需要讀取流到最後,顯然可以做到這一點。 – 2012-04-03 17:43:40