How to avoid HttpMessageNotReadableException
when using ContentCachingRequestWrapper
with Java Servlet Filters
If you're using a ContentCachingRequestWrapper
from Spring, you may be confused to find errors, similar to the below, from your application:
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 25 May 2020 15:45:29 GMT
Connection: close
{
"timestamp": "2020-05-25T15:45:33.739+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.String> me.jvt.hacking.controller.Controller.echo(java.lang.String)",
"path": "/"
}
This appears to be because the ContentCachingRequestWrapper
doesn't cache the raw ServletInputStream
, which is then consumed further down the line by Spring when trying to use @RequestBody
.
The solution is detailed in my article Reading a Servlet/Spring Request Body Multiple Times, and involves not using the ContentCachingRequestWrapper
, but instead using a custom class that can cache the ServletInputStream
.