java.io.IOException:通过https下载pdf时过早的EOF

时间:2012-04-26 12:19:32

标签: java http io stream

尝试使用java下载pdf时出错。我知道有类似的问题,但不像我的那样具体。

我的代码段:

URL url = new URL("https://.../abc.pdf");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
... 
InputStream in= conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
byte[] buf = new byte[4096];
int bytesRead = 0;
while ((bytesRead = in.read(buf)) != -1) {
    out.write(buf, 0, bytesRead);
}

Ther服务器响应标题:

 X-AspNet-Version:2.0.50727
 Transfer-Encoding:chunked
 Date:Thu 26 Apr 2012 12:07:59 GMT
 Content-Disposition:attachment; filename=abc.pdf
 Set-Cookie:Language=en-gb; path=/
 Connection:Keep-Alive
 Content-Type:application/octet-stream
 Server:Microsoft-IIS/6.0
 X-Powered-By:ASP.NET
 Cache-Control:private

例外(in.read(buf)):

Exception in thread "main" java.io.IOException: Premature EOF
    at sun.net.www.http.ChunkedInputStream.readAheadBlocking(ChunkedInputStream.java:556)
    at sun.net.www.http.ChunkedInputStream.readAhead(ChunkedInputStream.java:600)
    at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:687)
    at java.io.FilterInputStream.read(FilterInputStream.java:133)
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:2959)
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:2953)

该代码适用于几乎所有情况,并已使用了数千次。但在非常罕见的情况下,我得到了这个例外。但我可以用浏览器下载pdf。此外,如果我将pdf放在我自己的服务器上,我可以使用我的代码下载它。因此,它必须与服务器提供此pdf的方式有关。

也许它与Transfer-Encoding:chunked

有关

有人有想法,我可以尝试解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

这似乎是与java chunked处理相关的错误。许多人通过一次读取一个字节并将读取放在try-catch中来解决EOFException。