【问题标题】:Httpclien 4 gzip Post-DataHttpclient 4 gzip 后数据
【发布时间】:2013-07-23 22:16:48
【问题描述】:

我正在使用 httpclient 4. 当我使用时

new DecompressingHttpClient(client).execute(method)

客户端接受 gzip 并在服务器发送 gzip 时解压缩。

但是我怎样才能知道客户端发送的是压缩后的数据呢?

【问题讨论】:

    标签: http gzip apache-httpclient-4.x


    【解决方案1】:

    HttpClient 4.3 API:

    HttpEntity entity = EntityBuilder.create()
           .setText("some text")
           .setContentType(ContentType.TEXT_PLAIN)
           .gzipCompress()
           .build();
    

    HttpClient 4.2 API:

    HttpEntity entity = new GzipCompressingEntity(
         new StringEntity("some text", ContentType.TEXT_PLAIN));
    

    GzipCompressingEntity 实现:

     public class GzipCompressingEntity extends HttpEntityWrapper {
    
        private static final String GZIP_CODEC = "gzip";
    
        public GzipCompressingEntity(final HttpEntity entity) {
            super(entity);
        }
    
        @Override
        public Header getContentEncoding() {
            return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC);
        }
    
        @Override
        public long getContentLength() {
            return -1;
        }
    
        @Override
        public boolean isChunked() {
            // force content chunking
            return true;
        }
    
        @Override
        public InputStream getContent() throws IOException {
            throw new UnsupportedOperationException();
        }
    
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            final GZIPOutputStream gzip = new GZIPOutputStream(outstream);
            try {
                wrappedEntity.writeTo(gzip);
            } finally {
                gzip.close();
            }
        }
    
    }
    

    【讨论】:

    • 哇,谢谢.. 我已经找到了 4.2 版本,但是 4.3 看起来更好.. 我想我有 4.3
    猜你喜欢
    • 1970-01-01
    • 2011-03-06
    • 2017-11-03
    • 2015-07-24
    • 2011-02-16
    • 2018-01-11
    • 2021-08-14
    • 2021-10-29
    相关资源
    最近更新 更多