解決 org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected


異常翻譯:Premature end of chunk coded message body: closing chunk expected

翻譯如下:過早的關閉通過塊編碼的消息體:關閉塊異常。

關鍵點在於http傳輸協議1.0與1.1的區別,1.1協議的內容是分塊傳輸,response獲得實體事懶加載,一塊一塊的獲取,但是這個EntityUtils工具類的.toByteArray方法實現如下:

 public static byte[] toByteArray(final HttpEntity entity) throws IOException {
        Args.notNull(entity, "Entity");
        final InputStream instream = entity.getContent();
        if (instream == null) {
            return null;
        }
        try {
            Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
                    "HTTP entity too large to be buffered in memory");
            int capacity = (int)entity.getContentLength();
            if (capacity < 0) {
                capacity = DEFAULT_BUFFER_SIZE;
            }
            final ByteArrayBuffer buffer = new ByteArrayBuffer(capacity);
            final byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];
            int l;
            while((l = instream.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            return buffer.toByteArray();
        } finally {
            instream.close();
        }
    }
獲取結束立馬將流關閉了,但是傳輸還沒有結束了呢,所以就出現了上面的異常信息。

解決方案,設置http傳輸協議版本,改為1.0,這樣消息體就會一次性全部傳過來;

  HttpPost post = new HttpPost(builderUrl(url, requestParams));
  post.setProtocolVersion(HttpVersion.HTTP_1_0);

其他參考鏈接:

https://www.cnblogs.com/zengweiming/p/9364372.html

https://blog.csdn.net/c364902709/article/details/80828376

https://blog.csdn.net/u012175637/article/details/82467130


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM