【问题标题】:Spring @GetMapping with @RequestParam and @RequestBody fails with HttpMessageNotReadableException带有@RequestParam 和@RequestBody 的Spring @GetMapping 因HttpMessageNotReadableException 而失败
【发布时间】:2017-02-15 17:33:06
【问题描述】:

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

400 错误请求 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@GetMapping。我还是想不通为什么? @DeleteMapping@RequestBody 工作正常,根据 HTTP/1.1 GET 请求可能包含正文 - stackoverflow.com/questions/978061/http-get-with-request-body

IMO 允许 DELETE 中的 body 但禁止 GET 中看起来有点不一致

【问题讨论】:

    标签: spring http swagger spring-restcontroller


    【解决方案1】:

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

    作为一般规则,您只能将@RequestBody 用于可以包含“正文”内容的请求,例如POST 或 PUT。

    【讨论】:

    • Hmmm.... 但 GET 也可以有 body - elastic.co/guide/en/elasticsearch/reference/current/… Spring 允许使用 RequestBody 进行 GetMapping
    • 看看这一行,在同一篇文章中 - HTTP GET 和 HTTP POST 都可以用来执行带有正文的搜索。由于并非所有客户端都支持带有正文的 GET,因此也允许使用 POST。 根据 HTTP 标准,带有正文的 GET 请求是不正确的。
    • 那么,有什么意义 - Spring 不支持 GetMapping 的 RequestBody ?
    • Get 请求可以有 body 根据 HTTP/1.1 见 -stackoverflow.com/questions/978061/http-get-with-request-body
    • 没有编译错误,因为它是语法上有效的 Java 代码。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-23
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多