httpclient处理请求时进行gzip压缩和解压gizp响应结果

本文档记录了如何在使用HttpClient时,针对Content-Encoding:gzip的请求,进行请求参数的gzip压缩以及响应结果的解压缩。关键在于使用GzipCompressingEntity进行请求数据的压缩,以及GzipDecompressingEntity进行响应数据的解压缩。通过这段伪代码,开发者可以更好地理解和实现HttpClient中的gzip处理流程。
摘要由CSDN通过智能技术生成

最近开发的平台要求转发请求前判断如果请求头中带了Content-Encoding: gzip的情况下需先对请求参数进行gzip操作,网上找了好些时间也没有合适的代码可使用,看了一下源码后找到了以下解决方案可用在此记录一下。

发起请求前压缩关键伪代码:

HttpEntityEnclosingRequestBase request =
reqMethod.equals(HTTPConstants.POST) ? new HttpPost(uri) : new HttpPut(uri);
request.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
if (!StringUtils.isEmpty(bodyData)) {
request.setEntity(new StringEntity(bodyData));
// 压缩关键代码,使用了GzipCompressingEntity【关键代码】
request.setEntity(new GzipCompressingEntity(request.getEntity()));
}
HttpUriRequest httpRequest = request;                     
// 执行请求
CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, localContext)

解压缩响应结果关键伪代码(如果有需要unzip可参考以下代码):

CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, localContext)
// 解压关键代码,使用了GzipDecompressingEntity【关键代码】
GzipDecompressingEntity gzipEntity = new GzipDecompressingEntity(httpResponse.getEntity());
// 处理结果
sampleResult.setResponseData(this.readResponse(sampleResult, gzipEntity.getContent(), gzipEntity.getContentLength()));

关键点就是使用了httpclient提供的GzipCompressingEntity进行压缩,GzipDecompressingEntity进行解压缩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值