java.io.IOException:流在HandlerInterceptor中关闭

时间:2018-09-29 16:49:42

标签: java spring

SpringBoot中的Interceptor出现问题,我试图在preHandle()方法的请求中读取正文。

    public class LogInterceptor extends HandlerInterceptorAdapter  {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
 StringBuilder stringBuilder = new StringBuilder();  
            BufferedReader bufferedReader = null;  

            try {  
                InputStream inputStream = request.getInputStream(); 

                if (inputStream != null) {  
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));  

                    char[] charBuffer = new char[128];  
                    int bytesRead = -1;  

                    while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {  
                        stringBuilder.append(charBuffer, 0, bytesRead);  
                    }  
                } else {  
                    stringBuilder.append("");  
                }  
            } catch (IOException ex) {  
                System.out.println("Error reading the request body...");  
            } finally {  
                if (bufferedReader != null) {  
                    try {  
                        bufferedReader.close();  
                    } catch (IOException ex) {  
                        System.out.println("Error closing bufferedReader...");  
                    }  
                }  
            }


            String body = stringBuilder.toString();  
            System.out.println("--Body--"+body); 
    }
}

此代码可以正确打印正文,但是当我尝试与Postman进行POST请愿时,出现以下错误。

I/O error while reading input message; nested exception is java.io.IOException: Stream closed

如果我与此代码一起执行相同的请愿书,则请愿书将正常工作。

有人可以帮助我吗?还是说有更好的解决方案来拦截尸体?

0 个答案:

没有答案