Diana
Diana

Reputation: 1615

POST request not getting forwarded from Filter to Controller class

From postman I am hitting a post request like http://localhost:8084/abc/api/v1/xyz having payload and header. we have configured a Filter class extending GenericFilterBean before it hits the Controller. Its executing all the codes of Filter class fine but while executing 'chain.doFilter(request, response);' in the end to forward request to controller method its throwing below exception.In Filter class we are reading the payload and saving in audit table. In Controller class method we have parameters like @RequestBody annotaion, @Context HttpServletRequest, BindingResult.

18:59:25,779 INFO [stdout] (default task-1) 18:59:25,778||WARN |AbstractHandlerExceptionResolver:197|Resolved [org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: UT010029: Stream is closed]

Kindly suggest on this.

Upvotes: 0

Views: 2906

Answers (1)

ptomli
ptomli

Reputation: 11818

Is your filter reading the contents of the request? If so then you'll need to look at alternatives to this, as the input stream is not likely to be reusable without some assistance.

Can you post some code from the filter method?


Spring provides at least one mechanism to work around this, which might be helpful here, specifically the ContentCachingRequestWrapper. You can either create a new Filter which wraps the actual request in this wrapper, or you can simply make use of it yourself in your filter.

You might update your filter with something like this

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
   HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
   ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(currentRequest);

   // todo: your magic code, using wrappedRequest to access the body of the request

   // note: passing through the wrapped request,
   // which allows later handlers to also access the request
   chain.doFilter(wrappedRequest, servletResponse);
}

Note the documentation for ContentCachingRequestWrapper notes

HttpServletRequest wrapper that caches all content read from the input stream and reader, and allows this content to be retrieved via a byte array.

The error that you're receiving indicates you're reading the InputStream of the request, and you should rather simply access the getContentAsByteArray method of the wrapper.

Upvotes: 2

Related Questions