4

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

new DecompressingHttpClient(client).execute(method)

如果服务器发送 gzip,则客户端接受 gzip 并解压缩。

但是我怎样才能归档客户端发送它的压缩数据?

4

1 回答 1

6

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();
        }
    }

}
于 2013-07-25T19:49:17.287 回答