大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
编写Filter
/** * GZIP处理Filter */
@WebFilter(filterName = "httpServletGzipFilter", urlPatterns = "/")
public class HttpServletGzipFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request), response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
@Slf4j
class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
private HttpServletRequest request;
public HttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
}
/** * 根据 request header 的 Content-Encoding 判断是否启用 gzip 解压数据流 * @return * @throws IOException */
@Override
public ServletInputStream getInputStream() throws IOException {
ServletInputStream stream = request.getInputStream();
String contentEncoding = request.getHeader("Content-Encoding");
if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
try {
final GZIPInputStream gzipInputStream = new GZIPInputStream(stream);
ServletInputStream newStream = new ServletInputStream() {
@Override
public int read() throws IOException {
return gzipInputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
return newStream;
} catch (Exception e) {
log.error("uncompress content fail.", e);
}
}
return stream;
}
}
注册Filter交给Spring管理
@Configuration
public class HttpServletFilterConfig {
/** * 注册 HttpServletFilter * * @return */
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new HttpServletGzipFilter());
List<String> urlPatterns = new ArrayList<>();
urlPatterns.add("/*");
registrationBean.setUrlPatterns(urlPatterns);
return registrationBean;
}
}
Controller中获取Request body数据
public abstract class BaseController {
/** * 获取GZIP解压后的消息体 * * @param request * @return */
protected String getRequestBody(HttpServletRequest request) {
try {
ServletInputStream inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
测试验证
编写测试请求处理器,并使用okhttp进行验证。
@RestController
@RequestMapping("/gzip")
public class testController extends BaseController {
@RequestMapping(value = "/requstData")
public String requstData(HttpServletRequest request) {
return getRequestBody(request);
}
}
编写gzip测试类
public class GzipTest {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
@Test
public void gzipTest() {
String url = "http://localhost:8080/gzip/requstData";
String str = "%5-1sdf22322222sedssf测试sdklasdkgnfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff!@#$%^&****()_+=";
try {
String responseData = post(url, str);
System.out.println(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
public String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
// 通过GzipRequestInterceptor类拦截响应,自动处理gzip解压
.addInterceptor(new GzipRequestInterceptor())
.build();
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
// We don't know the compressed length in advance!
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
}
测试结果
参考文献
https://www.jianshu.com/p/a9d861732445
https://blog.csdn.net/aiynmimi/article/details/77453809
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/196427.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...