在拦截器中如果直接读取inputstream获取数据,会导致接口读取参数时参数为空,因为inputstream已经被读完,如何解决
时间: 2024-02-21 13:59:25 浏览: 88
springboot 解决InputStream只能读取一次的问题
5星 · 资源好评率100%
这是因为inputstream只能被读取一次,读取后就会被关闭。解决这个问题的方法是使用HttpServletRequestWrapper来包装HttpServletRequest对象,并重写getInputStream()方法和getReader()方法,使得在拦截器中读取inputstream不会影响接口读取参数。具体实现可参考以下示例代码:
```java
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = IOUtils.toByteArray(request.getInputStream());
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() {
return byteArrayInputStream.read();
}
};
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
```
在拦截器中,将HttpServletRequest对象包装成MyHttpServletRequestWrapper对象,再将包装后的对象传递给下一个过滤器或接口即可:
```java
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper(request);
// 将包装后的对象传递给下一个过滤器或接口
return true;
}
}
```
这样,即使在拦截器中读取了inputstream,也不会影响接口读取参数的正常获取。
阅读全文