专栏首页北漂的我解决:getReader() has already been called for this request

解决:getReader() has already been called for this request

在 Filter 中对 request 中的 body 进行参数签名校验, 会报如下错误:

getReader() has already been called for this request

原因是 request.getReader() 和 request.getInputStream() 都是只能调用一次

并且 getReader() 方法底层也是调用 getInputStream() 来实现的.

所以我们要使用 HttpServletRequestWrapper 来实现自定义的 CustomHttpServletRequestWrapper, 把 body 保存在 CustomHttpServletRequestWrapper 中, 并且重写 getInputStream() 方法

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper{

	private byte[] body;

	public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		
		BufferedReader reader = request.getReader();
		try (StringWriter writer = new StringWriter()) {
			int read;
            char[] buf = new char[1024 * 8];
    		while ((read = reader.read(buf)) != -1) {
    			writer.write(buf, 0, read);
    		}
    		this.body = writer.getBuffer().toString().getBytes();
        }
	}
	
	public byte[] getBody() {
		return body;
	}
	
	@Override
	public ServletInputStream getInputStream() throws IOException {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
		return new ServletInputStream() {
			
			@Override
			public int read() throws IOException {
				return byteArrayInputStream.read();
			}
			
			@Override
			public void setReadListener(ReadListener listener) {
			}
			
			@Override
			public boolean isReady() {
				return false;
			}
			
			@Override
			public boolean isFinished() {
				return false;
			}
		};
	}
}

然后, 获取 body 就调用 CustomHttpServletRequestWrapper 中的 getBody() 方法, 后面就使用

filterChain.doFilter(customHttpServletRequestWrapper, response);

就 OK 了

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • java.lang.IllegalStateException: getOutputStream() has already been called for this response

    https://stackoverflow.com/questions/33982515/handlerinterceptor-getoutputstream-...

    一个会写诗的程序员
  • getWriter() has already been called for this response 的解决办法

    潇洒
  • request和response接口

    热心的社会主义接班人
  • getWriter() has already been called for this response异常

    IllegalStateException: getWriter() has already been called for this response 从字面...

    似水的流年
  • fastjson——使用 aop 打印入参,报错:getOutputStream() has already been called for this response

    我在使用 aop 做日志切面,记录 controller 的入参和返回时,将参数使用 fastjson 格式化。代码如下:

    凡人飞
  • SAP CRM 中间件Request download里,遇到/SAPPSPRO/S_MAT_ENHANC_COMM 错误的解决办法

    SAP CRM 中间件Request download里,遇到/SAPPSPRO/S_MAT_ENHANC_COMM 错误的解决办法

    Jerry Wang
  • 解决HttpServletRequest#getIntputStream只能读一次

    以前一直自己封装一个Wrapper来缓存Body的内容,今天发现在Spring中已经帮我们实现了。就是org.springframework.web.util....

    DH镔
  • tomcat如何关闭response的outputStream

    在写文件下载的时候,遇到了一个问题,就是这个ServletOutputStream到底要不要自己flush以及close。这里以tomcat容易为例,解读一下。

    codecraft
  • FreeSwitch Hangup-Cause电话挂断原因速查

    Freeswitch官网太慢了,经常还打不开,把电话挂断原因大全复制一份到这里,方便日常查看

    菩提树下的杨过

扫码关注云+社区

领取腾讯云代金券