11.4.2 通过 POST 方式发送资源

使用 WebClient 发送数据与接收数据没有多大区别。例如,假设你拥有一个 Mono,并希望使用由 Mono 发布的 Ingredient 发送一个 POST 请求到具有 /ingredients 相对路径的 URI。

你所要做的就是使用 post() 方法而不是 get() 方法,并指定使用 Mono 调用 body() 来填充请求体:

Mono<Ingredient> ingredientMono = ...;

Mono<Ingredient> result = webClient
    .post()
    .uri("/ingredients")
    .body(ingredientMono, Ingredient.class)
    .retrieve()
    .bodyToMono(Ingredient.class);

result.subscribe(i -> { ... })

如果你没有要发送的 Mono 或 Flux,而是手头有原始域对象,你可以使用 syncBody()。例如,假设你要在请求体中发送的是一个 Ingredient 对象,而不是 Mono 对象:

Ingedient ingredient = ...;

Mono<Ingredient> result = webClient
    .post()
    .uri("/ingredients")
    .syncBody(ingredient)
    .retrieve()
    .bodyToMono(Ingredient.class);

result.subscribe(i -> { ... })

如果不是 POST 请求,而是要用 PUT 请求更新 Ingredient,则调用 put() 而不是 post() 并相应调整 URI 路径:

Mono<Void> result = webClient
    .put()
    .uri("/ingredients/{id}", ingredient.getId())
    .syncBody(ingredient)
    .retrieve()
    .bodyToMono(Void.class)
    .subscribe();

PUT 请求通常具有空的响应体,因此必须请求 bodyToMano() 返回类型为 Void 的 Mono。订阅该 Mono 时,将发送请求。

results matching ""

    No results matching ""