场景描述:

    在 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)


自己的报错(想把getReader输出两遍)



java.lang.IllegalStateException: getReader() has already been called for this request
org.apache.catalina.connector.Request.getInputStream(Request.java:1032)
org.apache.catalina.connector.RequestFacade.getInputStream(RequestFacade.java:364)
org.apache.commons.fileupload.servlet.ServletRequestContext.getInputStream(ServletRequestContext.java:112)
org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:952)
org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
com.cc8w.controller.TestController.upload(TestController.java:68)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)


 

原因分析:

    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);
}