首先,我检查了代理是否真的返回了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,所以我已经开了一个新的bug#7168608。
- 如果有人能帮我编写代码,应该返回直接FTP连接、通过代理的FTP连接和本地
file:/
URL的正确内容长度,我会非常感激。 - 如果使用JDK6无法解决此问题,请建议任何其他库,它一定适用于我提到的所有情况(Apache Http Client?)。