java.lang.IllegalStateException: getInputStream() has already been called for this request

背景

ExcelptionHandler中可以传入ServerletRequest作为入参,但是ServerletRequest的inputStream只能被读取一次,发生异常的时候再想去读取body只能悲催的得到一个已经Closed的Stream。

在使用HttpServletRequest获取post请求对象的方法如下

BufferedReader reader = req.getReader();
while (null != (line = reader.readLine())){
    data.append(line);
}

当某些时候, tomcat已经读取过一次了,导致抛异常!

java.lang.IllegalStateException: getInputStream() has already been called for this request

使用ContentCachingRequestWrapper

1. 通过过滤器将ServerletRequest封装成ContentCachingRequestWrapper,body被读取后,会被它缓存。

@Component
public class RequestWrapperFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse);
    }
}

2. ExceptionHandler传入ServletRequest,此时的ServletRequest就是ContentCachingRequestWrapper,输出即可

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Response> returnMediaTypeNotSupportError(Exception ex, ServletRequest request) {
        if (request != null && request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request;
            logger.error("request_body:{}", StringUtils.toEncodedString(wrapper.getContentAsByteArray(), Charset.forName(wrapper.getCharacterEncoding())));
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值