Java重写HttpServletRequestWrapper ,解决getInputStream()只能获取一次数据流的问题
项目基于springboot开发,RestFull接口向外暴露的API需要进行签名验证,即在进入真正controller方法前,需要先验证接口请求的有效性,所以需要对提交的POST流进行JSON读,并将相关参数进行验签。
package com.joshua317.blog.web.frame.filter; import org.springframework.util.StreamUtils; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * @author joshua317 on 2022/01/12 */ public class ResetRequestWrapper extends HttpServletRequestWrapper { private byte[] requestBody = null; public ResetRequestWrapper(HttpServletRequest request) throws IOException { super(request); //重点就是这里,把获取到的流数据重新复制给一个对象 requestBody = StreamUtils.copyToByteArray(request.getInputStream()); } @Override public ServletInputStream getInputStream() { final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody); return new ServletInputStream() { @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } @Override public int read() { return bais.read(); // 读取 requestBody 中的数据 } }; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } }