重复读取 HttpServletRequest 中 InputStream 的方法

CG国斌 2020-11-12 22:34:41
InputStream 读取 重复 复读 httpservletrequest


开篇第一句,大家是否遇到过这样的问题:

  • 通过httpServletRequest.getInputStream()获取InputStream之后,遇到Required request body is missing错误?

如果你回答“是”的话,那你就来对了。在本文中,我们就来讨论一下,

  • 问题 1:为什么InputStream无法重复读取?
  • 问题 2:如何重复读取HttpServletRequest中的InputStream

回答第一个问题

对于第一个问题,“为什么InputStream无法重复读取?”,最直接粗暴的回答:InputStream就是被设计为无法被重复读取的。

我们可以看一下InputStreamread()方法的注释:

 /**
* Reads the next byte of data from the input stream. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* <p> A subclass must provide an implementation of this method.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
public abstract int read() throws IOException;

翻译过来,其大意为:

  • 从输入流中读取下一个字节的数据。返回的字节值为从0255之间的int型数据。如果由于流到达结尾而没有可用的字节,则返回-1。除非有可用的输入数据、或者探测到已经到达流的末尾、或者抛出异常,否则将一直阻塞。

根据上面的注释中,我们可以很容易的得出结论:流中的数据,并不是一直存储的,而是会随着读取的行为,被消费掉

也许上面的解释很抽象,因此我们可以简单的将InputStream想象为装水的管子,随着水的流出,管子中的水早晚会有流尽的一天。

这么一想,InputStream到和 NIO 中的Buffer有些类似了,但无论是InputStream还是OutputStream都是单向的,要么只能进、要么只能出,而 NIO 中的Buffer则是双向的。

回答第二个问题

既然我们已经知道了InputStream无法被重复读取的原因,那么对于第二个问题,“如何重复读取HttpServletRequest中的InputStream?”,其解决方法就简单了。我们可以在获取HttpServletRequest中的InputStream的时候,同时做一个备份。

例如,先将HttpServletRequest中的InputStream取出来,转为String对象,然后再把String对象转为byte[]数组存回去,这就保证了HttpServletRequestInputStream的值不变,但是我们却获得了可以重复使用的String对象。

下面就给出一段可用的代码示例,能够保证我们安全的获取HttpServletRequest中的InputStream对象:

public class SafeHttpServletRequestWrapper extends HttpServletRequestWrapper {

private static final String CHARSET_UTF8 = "UTF-8";
private final byte[] body;
private String bodyString;
public SafeHttpServletRequestWrapper(HttpServletRequest request) throws IOException {

super(request);
this.bodyString = StreamUtils.copyToString(request.getInputStream(), Charset.forName(CHARSET_UTF8));
body = bodyString.getBytes(CHARSET_UTF8);
}
public String getBodyString() {

return this.bodyString;
}
@Override
public BufferedReader getReader() throws IOException {

return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {

final ByteArrayInputStream innerBAIS = new ByteArrayInputStream(body);
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() throws IOException {

return innerBAIS.read();
}
};
}
}

如上述代码所示,SafeHttpServletRequestWrapper是一个安全的HttpServletRequest包装类。使用方式为:

@Slf4j
public abstract class AbstractFilter implements Filter {

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

try {

SafeHttpServletRequestWrapper requestWrapper = new SafeHttpServletRequestWrapper((HttpServletRequest) servletRequest);
log.info("AbstractFilter servletRequest body is {}", requestWrapper.getBodyString());
filterChain.doFilter(requestWrapper, servletResponse);
} catch (IOException e) {

e.printStackTrace();
}
}
}

如上述代码所示,我们先将servletRequest强转成了HttpServletRequest,然后又包装成了SafeHttpServletRequestWrapper对象。在SafeHttpServletRequestWrapper对象中,就含有我们备份的InputStream对象(实际上,被包装成了ByteArrayInputStream对象)以及可用的bodyString字符串。

在这里,如果我们想要获取原HttpServletRequestInputStream对象的内容,我们直接调用getBodyString()即可;如果我们想要将HttpServletRequest继续传递下去,我们直接传递包装后的SafeHttpServletRequestWrapper即可,因为其已经包含了原HttpServletRequest中的全部信息,并且备份了InputStream对象的内容。


参考文献

版权声明
本文为[CG国斌]所创,转载请带上原文链接,感谢
https://guobinhit.blog.csdn.net/article/details/107387531

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple