異常處理:getReader() has already been called for this request
阿新 • • 發佈:2020-07-08
場景描述:
在 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); }
轉 :https://blog.csdn.net/magic_kid_2010/article/details/102782467