Springboot gzip 압축 풀기 http 데이터 흐름

31710 단어 봄 온 가족 통
필터 작성
/**
 * 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;
    }
}

컨트롤 러 에서 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

좋은 웹페이지 즐겨찾기