大家好,又见面了,我是你们的朋友全栈君。
/** * 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;
}
}
@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;
}
}
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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/196427.html原文链接:https://javaforall.cn