尝试使用 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);
}
其他服务器响应标头:
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
?
有谁知道,我可以尝试解决这个问题吗?