Apache httpclient:块编码消息正文的过早结束:预期关闭块

时间:2019-11-12 07:02:47

标签: java httpclient

我使用httpclient-4.5.2下载了一些pdf文件,但有时失败并抛出closeException。 Google上的一些答案是关于过早关闭响应。但是我仔细检查了我的代码,并没有在关闭响应后尝试读取数据。这个问题还有其他原因吗?

org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
        at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:266)
        at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:225)
        at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:184)
        at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
        at java.io.FilterInputStream.read(FilterInputStream.java:107)
        HttpGet httpGet = new HttpGet(fileUrl);
        try (CloseableHttpClient httpclient1 = HttpClients.createDefault()){
            httpGet.setHeader("Cookie", cookie);
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
            try (CloseableHttpResponse response = httpclient1.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                File file = new File(tarPath);
                if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
                    throw new IOException("Failed to create download directory");
                }
                byte[] b = new byte[1024];
                try (
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(fos)
                ) {
                    int len;
                    while ((len = is.read(b)) != -1) { // the exception is thrown from here: is.read(b)
                        bos.write(b, 0, len);
                    }
                }
            }
       }

0 个答案:

没有答案