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