[英]Spring @GetMapping with @RequestParam and @RequestBody fails with HttpMessageNotReadableException
Request to the endpoint fails with the following error:对端点的请求失败并出现以下错误:
400 Bad request org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
400 错误请求 org.springframework.http.converter.HttpMessageNotReadableException:缺少所需的请求正文
@GetMapping
public List<SomeObject> list(@RequestParam(required = false) String parameter, @RequestBody String body, @RequestHeader("Authorization") String token) {
.....
}
if @GetMapping
would be changed to @PostMapping
everything works like a charm though.如果
@GetMapping
将更改为@PostMapping
一切都像魅力一样。 Any ideas what the heck is going on ?任何想法到底发生了什么?
NOTE: Swagger is used for request sending, so it is quite unlikely that the error is in Curl注意: Swagger 用于请求发送,因此错误不太可能出现在 Curl 中
UPDATE: So, it looks like Spring does not support @RequestBody
for @GetMapping
.更新:因此,Spring 似乎不支持
@GetMapping
@RequestBody
。 I still can not figure out why ?我还是想不通为什么?
@DeleteMapping
with @RequestBody
works fine and according to HTTP/1.1 GET requests could potentially contain the body - stackoverflow.com/questions/978061/http-get-with-request-body @DeleteMapping
与@RequestBody
工作正常,根据 HTTP/1.1 GET 请求可能包含正文 - stackoverflow.com/questions/978061/http-get-with-request-body
IMO it looks a bit inconsistent to allow body in DELETE
but forbid in GET
IMO 在
DELETE
允许 body 但在GET
禁止它看起来有点不一致
@RequestBody
annotation binds the content sent in (POST / PUT) request body with the annotated variable. @RequestBody
注解将在(POST / PUT)请求正文中发送的内容与带注解的变量绑定。 Since there is no 'body' part in GET request, spring throws HttpMessageNotReadableException to indicate the same.由于 GET 请求中没有“正文”部分,因此 spring 会抛出 HttpMessageNotReadableException 以指示相同。
As a general rule, you can only use @RequestBody
for the requests which can have 'body' content eg POST or PUT.作为一般规则,您只能将
@RequestBody
用于可以具有“正文”内容的请求,例如 POST 或 PUT。
I met the similar problem today in spring-webmvc 5.1.5 and checked the library code.今天在spring-webmvc 5.1.5遇到了类似的问题,查了库代码。 The
HttpMessageNotReadableException
was thrown from RequestResponseBodyMethodProcessor.readWithMessageConverters
since it invoked readWithMessageConverters
and got null. HttpMessageNotReadableException
是从RequestResponseBodyMethodProcessor.readWithMessageConverters
抛出的,因为它调用了readWithMessageConverters
并得到了 null。 There is an loop in readWithMessageConverters
searching suitable converter for the request Content-Type ( for (HttpMessageConverter<?> converter : this.messageConverters)
), and because I didn't specify and Content-Type in request, it failed. readWithMessageConverters
有一个循环为请求 Content-Type 搜索合适的转换器( for (HttpMessageConverter<?> converter : this.messageConverters)
),因为我没有在请求中指定 Content-Type ,所以它失败了。
So I specified the header Content-Type: application/json
and solved the problem.所以我指定了标题
Content-Type: application/json
并解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.