问题描述:
在spring boot的拦截器中,读取ServletRequest中的内容,抛出异常:getReader() has already been called for this request异常
原因:
ServletRequest的getReader()和getInputStream()两个方法只能被调用一次
解决办法:
先将 Request Body 保存,然后通过 Servlet 自带的 HttpServletRequestWrapper 类覆盖 getReader() 和getInputStream() 方法,使流从保存的body读取。然后再Filter中将ServletRequest替换为AuthenticationRequestWrapper。
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String 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);
}
// cache play load when create wrapper
body = sb.toString();
}
public String getBody() {
return body;
}
}
try {
MyRequestWrapper myRequestWrapper = new MyRequestWrapper(request);
return myRequestWrapper.getBody();
} catch (IOException e) {
log.error("get request body exception", e);
throw new RuntimeException(e);
}