I used @RequestBody
to parse HttpServletRequest
body data in my POST method. I repeatedly submit POST request, and possibly the jsonArray is null, but contentLength is not 0.
@PostMapping("xxx")
public void verify(@RequestBody(required = false)String jsonArray, HttpServletRequest request, HttpServletResponse response)
{
if (jsonArray == null || jsonArray.length() == 0) {
int contentLength = request.getContentLength();
logger.error("contentLength= " + contentLength);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
Comment From: s-c-c
the spring boot version is v2.2.5, and i post https request, not http, because http works fine.
Comment From: snicoll
@RequestBody
is part of the Spring Framework and such binding isn't done in Spring Boot so I am going to move this issue to the appropriate issue tracker.
sometimes the string is null.
It's hard for us to figure out if there is an issue in Spring Framework based on that. To make hopefully some progress, please share a minimal sample that we can run ourselves that reproduces the issue. You can do so by attaching a zip to this issue or sharing the url to a GitHub repository.
Comment From: sbrannen
Have you tried removing required = false
from the @RequestBody
declaration?
Comment From: s-c-c
The possible cause is that the remaining data has not arrived, inputStream cannot read the data and return -1 in advance.
Comment From: s-c-c
I tried to remove @RequestBody and read the body data manually. It will be ok.
public String getJsonFromRequest(HttpServletRequest request) {
String json = null;
try(InputStream inputStream = request.getInputStream()) {
int len = request.getContentLength();
byte[] buff = new byte[len];
int readLen = 0;
int time = 0;
for (int i = 0; time < READ_RETRY_TIME && i < len;) {
readLen = inputStream.read(buff, i, len - i);
if (readLen != -1) {
i+= readLen;
} else {
Thread.sleep(1000);
time++;
}
}
json = new String(buff, "UTF-8");
} catch (IOException e) {
} catch (InterruptedException e) {
}
return json;
}
Comment From: rstoyanchev
If you'd like us to look further please provide clear instructions on how to reproduce the issue. To be more specific, you have shown server side code, but no details on what requests need to be submitted in order to observe the issue.
Comment From: spring-projects-issues
If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.
Comment From: s-c-c
the cause of the problem is that the server read -1 while the data havent totally submited by client. for example, the content len i get from request is 12396. but i read -1 when i read the 8397 byte data. i dont know why this hanpen.
Comment From: snicoll
Given that we didn't get the instruction to reproduce the issue as requested, I am going to close this. We can reconsider if a sample is provided.