Java报错解决:org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closi

在运行Java爬虫时遇到org.apache.http.ConnectionClosedException错误。尝试了升级Apache HttpClient到最新版本4.5.8和将HttpClients放入try块中,但问题仍未完全解决。寻求更多解决建议。

再跑爬虫程序的时候突然遇到了如下报错:

org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected...
        at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:263)
        at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:222)
        at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:183)
        at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:135)
        at java.base/java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:243)
        at java.base/java.util.zip.InflaterInputStream.read(InflaterInputStream.java:159)
        at java.base/java.util.zip.GZIPInputStream.read(GZIPInputStream.java:118)
        at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:70)
        at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
        at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
        at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
        at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
        at java.base/java.io.Reader.read(Reader.java:229)
        at org.apache.http.util.EntityUtils.toString(EntityUtils.java:227)
        at org.apache.http.util.EntityUtils.toString(EntityUtils.java:308)

网上查找资料如何解决这个问题。

解决方法1

先在GitHub上看到了这个issue:ApacheConnector could throw ConnectionClosedException when using httpclient: 4.5.1+ with chunked transfer encoding · Issue #3629 · jersey/jersey

这个issue的解法方法是把org.apache.httpcomponents升级到最新的版本。

2019-5-26: 最新版本是4.5.8:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.8</version>
</dependency>

解决方法2

我在网上找到了另外一篇博客:httpclient在获取response的entity时报异常 - 枯木fc - 博客园
但还是没有找到好的解决方法。
现在我的解决方法是把HttpClients放进try的括号中:

        try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
        } catch (Exception e) {
            e.printStackTrace();
        }

有其他解决方法的欢迎评论告诉我。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值