Method of repeatedly reading InputStream in HttpServletRequest

CG Guobin 2020-11-12 22:34:41
method repeatedly reading inputstream httpservletrequest

The first sentence of the opening , Have you ever encountered such a problem :

  • adopt httpServletRequest.getInputStream() obtain InputStream after , encounter Required request body is missing error ?

If you answer “ yes ” Words , Then you're right . In this paper , Let's talk about ,

  • problem 1: Why? InputStream Can't read repeatedly ?
  • problem 2: How to read repeatedly HttpServletRequest Medium InputStream

Answer the first question

For the first question ,“ Why? InputStream Can't read repeatedly ?”, The most direct and rude answer :InputStream It's designed to be unreadable .

We can have a look InputStream in read() Method comments :

* 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;

Translate it , Its main idea is :

  • Read the next byte of data from the input stream . The byte value returned is from 0 To 255 Between int Type data . If no bytes are available because the stream reaches the end , Then return to -1. Unless there's input data available 、 Or the end of the stream has been detected 、 Or throw an exception , Otherwise, it will be blocked all the time .

According to the note above , We can easily conclude that : Data in the stream , It's not always stored , It will follow the behavior of reading , Be consumed .

Maybe the above explanation is abstract , So we can simply put InputStream Imagine a pipe filled with water , With the flow of water , The water in the pipe will run out sooner or later .

Think about it ,InputStream To and NIO Medium Buffer It's kind of like , But neither InputStream still OutputStream It's all one-way , Or you can only go in 、 Or it can only come out of , and NIO Medium Buffer It's two-way .

Answer the second question

Now that we know InputStream The reason why it can't be read repeatedly , So for the second question ,“ How to read repeatedly HttpServletRequest Medium InputStream?”, The solution is simple . We can get HttpServletRequest Medium InputStream When , Make a backup at the same time .

for example , First the HttpServletRequest Medium InputStream out , To String object , Then take it. String Object to byte[] Save the array back , That's the guarantee HttpServletRequest in InputStream The value of does not change , But we get reusable String object .

Here is an example of the code available , Can guarantee our safe access to HttpServletRequest Medium InputStream object :

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 {

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

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

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

final ByteArrayInputStream innerBAIS = new ByteArrayInputStream(body);
return new ServletInputStream() {

public boolean isFinished() {

return false;
public boolean isReady() {

return false;
public void setReadListener(ReadListener readListener) {

public int read() throws IOException {


As shown in the above code ,SafeHttpServletRequestWrapper It's a safe HttpServletRequest Packaging . Use mode: :

public abstract class AbstractFilter implements Filter {

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

try {

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


As shown in the above code , We will first servletRequest It turned into HttpServletRequest, And then it was packaged as SafeHttpServletRequestWrapper object . stay SafeHttpServletRequestWrapper In the object , It contains our backup InputStream object ( actually , It's packaged as ByteArrayInputStream object ) And the available bodyString character string .

ad locum , If we want to get the original HttpServletRequest in InputStream Object content , We call directly getBodyString() that will do ; If we want to HttpServletRequest Pass it on , We deliver the packaged SafeHttpServletRequestWrapper that will do , Because it already contains the original HttpServletRequest All the information in , And back up InputStream Object content .


本文为[CG Guobin]所创,转载请带上原文链接,感谢

  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