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

时间:2017-02-15 17:33:06

标签: spring http swagger spring-restcontroller

对端点的请求失败,并显示以下错误:

  

400 Bad request   org.springframework.http.converter.HttpMessageNotReadableException:   缺少必需的请求正文

@GetMapping
public List<SomeObject> list(@RequestParam(required = false) String parameter, @RequestBody String body, @RequestHeader("Authorization") String token) {
.....
}

如果将@GetMapping更改为@PostMapping,那么一切都像魅力一样。 任何想法到底发生了什么?

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

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

IMO看起来有点不一致,允许@RequestBody中的正文,但禁止DELETE

2 个答案:

答案 0 :(得分:7)

@RequestBody注释将(POST / PUT)请求体中发送的内容与带注释的变量绑定在一起。因为没有&#39;身体&#39;在GET请求中,spring抛出HttpMessageNotReadableException来表示相同。

作为一般规则,您只能将@RequestBody用于可以拥有&#39; body&#39;内容例如POST或PUT。

答案 1 :(得分:0)

我今天在spring-webmvc 5.1.5中遇到了类似的问题,并检查了库代码。 HttpMessageNotReadableException是从RequestResponseBodyMethodProcessor.readWithMessageConverters抛出的,因为它调用了readWithMessageConverters并为空。 readWithMessageConverters中有一个循环,正在为请求的Content-Type(for (HttpMessageConverter<?> converter : this.messageConverters))搜索合适的转换器,并且由于我没有在请求中指定Content-Type,所以失败了。

所以我指定了标题Content-Type: application/json并解决了问题。

相关问题