Issue
I have and Interceptor and for some reasons i have to read POSTED date included in HttpServletRequest
like this:
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
after this action i get 400 bad request for ajax
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
Solution
Spring provides a class called ContentCachingRequestWrapper
which extends HttpServletRequestWrapper
. This class caches all content read from
the getInputStream()
and getReader()
and allows this content to be retrieved via a getContentAsByteArray()
. So we can retrieve InputStream
multiple times for this purpose. This ability provided by method blow in ContentCachingRequestWrapper
:
@Override
public ServletInputStream getInputStream() throws IOException {
if (this.inputStream == null) {
this.inputStream = new ContentCachingInputStream(getRequest().getInputStream());
}
return this.inputStream;
}
This class fix character encoding issues for UTF-8
with method below:
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
}
Here is full detail in ContentCachingRequestWrapper
.
Answered By - Hadi Rasouli
Answer Checked By - Pedro (JavaFixing Volunteer)