2013-07-24 28 views
2

我使用的HttpClient 4.当我使用Httpclien 4 gzip的后数据

new DecompressingHttpClient(client).execute(method) 

客户acccepts gzip和如果服务器发送的gzip解压缩。

但是,我怎么能archieve,客户端发送它的数据gzipped?

回答

4

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

} 
+0

哇感谢..我已经找到了4.2版本,但4.3看起来更好..它我有4.3 – wutzebaer