乐趣区

关于springboot:108拦截器获取请求body

定义一个拦截器:

@Component
public class SjcjInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if (!(handler instanceof HandlerMethod)) {return true;}
        String token = request.getHeader("token");
        RequestWrapper requestWrapper = new RequestWrapper(request);
        String body = (String)requestWrapper.getAttribute("body");
        return true;
    }
    
}

定义一个申请 wrapper

public class RequestWrapper extends HttpServletRequestWrapper {private static Logger logger = LoggerFactory.getLogger(RequestWrapper.class);

    private String body;

    public RequestWrapper(HttpServletRequest request) {super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {inputStream = request.getInputStream();
            if (inputStream != null) {
                String charsetName = "UTF-8";
                String contentType = request.getHeader("Content-Type");
                if (!(StrUtil.isBlank(contentType) || "undefined".equals(contentType))) {contentType = contentType.replaceAll("","");
                    // application/json; charset=utf-8
                    String[] contentTypeArr = contentType.split(";");
                    for (String str : contentTypeArr) {if (str.startsWith("charset=")) {charsetName = str.substring(8);
                            break;
                        }
                    }
                }
                logger.info("defaultCharsetName: {}", Charset.defaultCharset().name());
                logger.info("charsetName: {}", charsetName);
                if (StrUtil.isBlank(charsetName) || "undefined".equals(charsetName)) {bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                } else {bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charsetName));
                }

                String str = null;
                while ((str = bufferedReader.readLine()) != null) {stringBuilder.append(str);
                }
            } else {stringBuilder.append("");
            }
        } catch (IOException ex) {logger.error("body 读取失败");
            logger.error(ex.getMessage());
        } finally {if (inputStream != null) {
                try {inputStream.close();
                } catch (IOException e) {e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {bufferedReader.close();
                } catch (IOException e) {e.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();}

    @Override
    public ServletInputStream getInputStream() throws IOException {final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {return false;}

            @Override
            public boolean isReady() {return false;}

            @Override
            public void setReadListener(ReadListener readListener) { }

            @Override
            public int read() throws IOException {return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

    @Override
    public BufferedReader getReader() throws IOException {return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }


    public String getBody() {return this.body;}

    public void setBody(String body) {this.body = body;}
}

定义 RequestFilter

@Component
public class CustomRequestFilter extends OncePerRequestFilter {private static Logger logger = LoggerFactory.getLogger(CustomRequestFilter.class);

    private String aesSecret = "B16883417B43599B6AF58A0E8769F46D";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {RequestWrapper requestWrapper = new RequestWrapper(request);
        if(requestWrapper == null) {filterChain.doFilter(request, response);
        } else {String body = requestWrapper.getBody();
           
           // 在这里能够批改 body 的内容
           // requestWrapper.setBody(obj);
            requestWrapper.setAttribute("body",body);
            filterChain.doFilter(requestWrapper, response);
        }
    }
}
退出移动版