我正在使用httpclient 4.当我使用
时new DecompressingHttpClient(client).execute(method)
如果服务器发送gzip,客户端会接受gzip并解压缩。
但我怎么能表示客户端发送数据gzipped?
答案 0 :(得分:5)
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();
}
}
}