首页 > 解决方案 > 使用 WebFlux 时如何使用 HTTP DELETE 发送正文?

问题描述

我想访问一个提供DELETE端点的 HTTP API。这个特定的端点需要一个项目列表(我想删除)作为 JSON 正文。

现在,我的问题是,我正在使用 Spring Webflux。但是它的WebClient并没有给我发送带有DELETE请求的正文的可能性。对于 a POST,我会这样做:

webClient.post()
         .uri("/foo/bar")
         .body(...)
         .exchange()

但是对于DELETE,我得到一个RequestHeadersSpec没有给我提供一个选项body(...)

webClient.delete()
         .uri("/foo/bar")
         .body(...)       <--- METHOD DOES NOT EXIST
         .exchange()

那么,在客户端使用 Spring Webflux 实现这一点的方法是什么?

标签: javaspringhttpspring-webflux

解决方案


您可以使用 webClient 的method()运算符。简单的例子,

return webClient
        .method(HttpMethod.DELETE)
        .uri("/delete")
        .body(BodyInserters.fromProducer(Mono.just(new JSONObject().put("body","stringBody").toString()), String.class))
        .exchange() 

推荐阅读