• 解决 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

  • 相关阅读:
    CF919F A Game With Numbers
    CF1005F Berland and the Shortest Paths
    CF915F Imbalance Value of a Tree
    CF1027F Session in BSU
    CF1029E Tree with Small Distances
    CF1037E Trips
    CF508E Arthur and Brackets
    CF1042F Leaf Sets
    [HNOI2012]永无乡
    [BZOJ1688][Usaco2005 Open]Disease Manangement 疾病管理
  • 原文地址:https://www.cnblogs.com/interdrp/p/12460260.html
Copyright © 2020-2023  润新知