带有@RequestParam 和@RequestBody 的Spring @GetMapping 因HttpMessageNotReadableException 而失败RequestBody、Re

2023-09-07 13:47:52 作者:初吻献给奶嘴

对端点的请求失败并出现以下错误:

Request to the endpoint fails with the following error:

400 错误请求org.springframework.http.converter.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 一切都像魅力一样工作.有什么想法吗?

if @GetMapping would be changed to @PostMapping everything works like a charm though. Any ideas what the heck is going on ?

注意: Swagger 用于发送请求,因此错误不太可能出现在 Curl 中

NOTE: Swagger is used for request sending, so it is quite unlikely that the error is in Curl

更新:因此,看起来 Spring 不支持 @GetMapping@RequestBody.我还是想不通为什么?@DeleteMapping@RequestBody 工作正常,根据 HTTP/1.1 GET 请求可能包含正文 - stackoverflow.com/questions/978061/http-get-with-request-身体

UPDATE: So, it looks like Spring does not support @RequestBody for @GetMapping. 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

IMO 在 DELETE 中允许正文但在 GET

IMO it looks a bit inconsistent to allow body in DELETE but forbid in GET

推荐答案

@RequestBody 注解将(POST/PUT)请求体中发送的内容与注解变量绑定.由于 GET 请求中没有body"部分,因此 spring 会抛出 HttpMessageNotReadableException 来表示相同.

@RequestBody annotation binds the content sent in (POST / PUT) request body with the annotated variable. Since there is no 'body' part in GET request, spring throws HttpMessageNotReadableException to indicate the same.

作为一般规则,您只能将 @RequestBody 用于可以具有正文"内容的请求,例如POST 或 PUT.

As a general rule, you can only use @RequestBody for the requests which can have 'body' content e.g. POST or PUT.