代码改变世界
[登录 · 注册]
  • 解决 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

  • 【推广】 阿里云小站-上云优惠聚集地(新老客户同享)更有每天限时秒杀!
    【推广】 云服务器低至0.95折 1核2G ECS云服务器8.1元/月
    【推广】 阿里云老用户升级四重礼遇享6.5折限时折扣!
  • 原文:https://www.cnblogs.com/interdrp/p/12460260.html
走看看 - 开发者的网上家园