Java http gzip压缩_httpclient对gzip响应内容解压

在使用Java HttpClient进行HTTP请求时,默认不会处理gzip压缩的响应内容。需要通过添加请求和响应拦截器来实现gzip解压。示例代码展示了如何添加拦截器并解压gzip内容。
摘要由CSDN通过智能技术生成

httpclient默认是不会对gzip格式解压的,需要手动处理一下,代码如下:

DefaultHttpClient httpclient = new DefaultHttpClient();

httpclient.addRequestInterceptor(new HttpRequestInterceptor() {

public void process(

final HttpRequest request,

final HttpContext context) throws HttpException, IOException {

if (!request.containsHeader("Accept-Encoding")) {

request.addHeader("Accept-Encoding", "gzip");

}

}

});

httpclient.addResponseInterceptor(new HttpResponseInterceptor() {

public void process(

final HttpResponse response,

final HttpContext context) throws HttpException, IOException {

HttpEntity entity = response.getEntity();

Header ceheader = entity.getContentEncoding();

if (ceheader != null) {

HeaderElement[] codecs = ceheader.getElements();

for (int i = 0; i < codecs.length; i++) {

if (codecs[i].getName().equalsIgnoreCase("gzip")) {

response.setEntity(

new GzipDecompressingEntity(response.getEntity()));

return;

}

}

}

}

});

HttpGet httpget = new HttpGet("http://www.apache.org/");

// Execute HTTP request

System.out.println("executing request " + httpget.getURI());

HttpResponse response = httpclient.execute(httpget);

System.out.println("----------------------------------------");

System.out.println(response.getStatusLine());

System.out.println(response.getLastHeader("Content-Encoding"));

System.out.println(response.getLastHeader("Content-Length"));

System.out.println("----------------------------------------");

HttpEntity entity = response.getEntity();

if (entity != null) {

String content = EntityUtils.toString(entity);

System.out.println(content);

System.out.println("----------------------------------------");

System.out.println("Uncompressed size: "+content.length());

}

// When HttpClient instance is no longer needed,

// shut down the connection manager to ensure

// immediate deallocation of all system resources

httpclient.getConnectionManager().shutdown();

参考:http://alvinalexander.com/java/jwarehouse/commons-httpclient-4.0.3/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java.shtml

http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientGZipContentCompression.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值