12.4.2 发送资源

使用 WebClient 发送数据与接收数据没有多大区别。例如,假设您拥有一个 Mono,并希望使用由 Mono 发布的 Ingredient 发送一个 POST 请求到具有 /ingredients 相对路径的 URI。您所要做的就是使用 post() 方法而不是 get() 方法,并指定使用 Mono 调用 body() 来填充请求体:

Mono<Ingredient> ingredientMono = Mono.just(
    new Ingredient("INGC", "Ingredient C", Ingredient.Type.VEGGIES));

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

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

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

IIngedient ingredient = ...;

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

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

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

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

result.subscribe();

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

results matching ""

    No results matching ""