Spring @GetMapping与@RequestParam和@RequestBody失败,并带有HttpMessageNotReadableException [英] Spring @GetMapping with @RequestParam and @RequestBody fails with HttpMessageNotReadableException

查看:840
本文介绍了Spring @GetMapping与@RequestParam和@RequestBody失败,并带有HttpMessageNotReadableException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.我还是不知道为什么?带有@RequestBody@DeleteMapping可以正常工作,并且根据HTTP/1.1,GET请求可能包含正文-stackoverflow.com/questions/978061/http-get-with-request-body

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.

这篇关于Spring @GetMapping与@RequestParam和@RequestBody失败,并带有HttpMessageNotReadableException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆