场景描述:
在 Spring Boot 自定义拦截器中,需要对请求 body 中的内容做签名验证。在日志切面中,需要打印请求 body 中的内容。
报错内容:
java.lang.IllegalStateException: getReader() has already been called for this request
at org.apache.catalina.connector.Request.getInputStream(Request.java:1069)
at org.apache.catalina.connector.RequestFacade.getInputStream(RequestFacade.java:365)
at com.igg.aggregate.server.aspect.LogAspect.before(LogAspect.java:80)
原因分析:
HttpServletRequest 的 getInputStream() 和 getReader() 都只能读取一次,由于 Request Body 是流的形式读取,那么
流读了一次就没有了,所以只能被调用一次。
解决办法:
先将 Request Body 保存,然后通过 Servlet 自带的 HttpServletRequestWrapper 类覆盖 getReader() 和
getInputStream() 方法,使流从保存的body读取。然后再Filter中将ServletRequest替换为AuthenticationRequestWrapper。
代码示例:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private byte[] body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String body = sb.toString();
this.body = body.getBytes(StandardCharsets.UTF_8);
}
public String getBody() {
return new String(body, StandardCharsets.UTF_8);
}
}
// 获取请求body
try {
MyRequestWrapper myRequestWrapper = new MyRequestWrapper(request);
return myRequestWrapper.getBody();
} catch (IOException e) {
log.error("get request body exception", e);
throw new RuntimeException(e);
}
解决:getReader() has already been called for this request
2020-12-28阅读 2.7K0在 Filter 中对 request 中的 body 进行参数签名校验, 会报如下错误:
getReader() has already been called for this request
原因是 request.getReader() 和 request.getInputStream() 都是只能调用一次
并且 getReader() 方法底层也是调用 getInputStream() 来实现的.
所以我们要使用 HttpServletRequestWrapper 来实现自定义的 CustomHttpServletRequestWrapper, 把 body 保存在 CustomHttpServletRequestWrapper 中, 并且重写 getInputStream() 方法
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper{ private byte[] body; public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); BufferedReader reader = request.getReader(); try (StringWriter writer = new StringWriter()) { int read; char[] buf = new char[1024 * 8]; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); } this.body = writer.getBuffer().toString().getBytes(); } } public byte[] getBody() { return body; } @Override public ServletInputStream getInputStream() throws IOException { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return byteArrayInputStream.read(); } @Override public void setReadListener(ReadListener listener) { } @Override public boolean isReady() { return false; } @Override public boolean isFinished() { return false; } }; } }
然后, 获取 body 就调用 CustomHttpServletRequestWrapper 中的 getBody() 方法, 后面就使用
filterChain.doFilter(customHttpServletRequestWrapper, response);
就 OK 了