栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

最近开发的平台要求转发请求前判断如果请求头中带了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进行解压缩。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号