Spring 带有@RequestParam 和@RequestBody 的@GetMapping 因HttpMessageNotReadableException 而失败
Spring @GetMapping with @RequestParam and @RequestBody fails with HttpMessageNotReadableException
对端点的请求失败,出现以下错误:
400 Bad request
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing
@GetMapping
public List<SomeObject> list(@RequestParam(required = false) String parameter, @RequestBody String body, @RequestHeader("Authorization") String token) {
.....
}
如果 @GetMapping
将更改为 @PostMapping
一切都像魅力一样。
知道到底发生了什么吗?
NOTE: Swagger 用于请求发送,因此错误在 Curl 中的可能性很小
更新:
所以,看起来 Spring 不支持 @GetMapping
的 @RequestBody
。我还是不明白为什么? @DeleteMapping
和 @RequestBody
工作正常,根据 HTTP/1.1 GET 请求可能包含正文 - Whosebug。com/questions/978061/http-get-with-request-body
IMO 在 DELETE
中允许正文但在 GET
中禁止正文看起来有点不一致
@RequestBody
注释将在 (POST / PUT) 请求正文中发送的内容与注释变量绑定。由于 GET 请求中没有 'body' 部分,因此 spring 抛出 HttpMessageNotReadableException 以表明相同。
作为一般规则,您只能对可以包含 'body' 内容的请求使用 @RequestBody
,例如POST 或 PUT.
今天在spring-webmvc5.1.5遇到了类似的问题,查看了库代码。 HttpMessageNotReadableException
是从 RequestResponseBodyMethodProcessor.readWithMessageConverters
中抛出的,因为它调用了 readWithMessageConverters
并得到了 null。 readWithMessageConverters
中有一个循环为请求Content-Type(for (HttpMessageConverter<?> converter : this.messageConverters)
)寻找合适的转换器,因为我没有在请求中指定和Content-Type,所以失败了。
所以我指定了 header Content-Type: application/json
并解决了问题。
对端点的请求失败,出现以下错误:
400 Bad request org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
@GetMapping
public List<SomeObject> list(@RequestParam(required = false) String parameter, @RequestBody String body, @RequestHeader("Authorization") String token) {
.....
}
如果 @GetMapping
将更改为 @PostMapping
一切都像魅力一样。
知道到底发生了什么吗?
NOTE: Swagger 用于请求发送,因此错误在 Curl 中的可能性很小
更新:
所以,看起来 Spring 不支持 @GetMapping
的 @RequestBody
。我还是不明白为什么? @DeleteMapping
和 @RequestBody
工作正常,根据 HTTP/1.1 GET 请求可能包含正文 - Whosebug。com/questions/978061/http-get-with-request-body
IMO 在 DELETE
中允许正文但在 GET
@RequestBody
注释将在 (POST / PUT) 请求正文中发送的内容与注释变量绑定。由于 GET 请求中没有 'body' 部分,因此 spring 抛出 HttpMessageNotReadableException 以表明相同。
作为一般规则,您只能对可以包含 'body' 内容的请求使用 @RequestBody
,例如POST 或 PUT.
今天在spring-webmvc5.1.5遇到了类似的问题,查看了库代码。 HttpMessageNotReadableException
是从 RequestResponseBodyMethodProcessor.readWithMessageConverters
中抛出的,因为它调用了 readWithMessageConverters
并得到了 null。 readWithMessageConverters
中有一个循环为请求Content-Type(for (HttpMessageConverter<?> converter : this.messageConverters)
)寻找合适的转换器,因为我没有在请求中指定和Content-Type,所以失败了。
所以我指定了 header Content-Type: application/json
并解决了问题。