【问题标题】:How to create request with parameters with webflux Webclient?如何使用 webflux Webclient 创建带参数的请求?
【发布时间】:2018-02-16 14:11:09
【问题描述】:

在后端我有带有 POST 方法的 REST 控制器:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public Integer save(@RequestParam String name) {
   //do save
   return 0;
}

如何使用带有请求参数的WebClient 创建请求?

WebClient.create(url).post()
    .uri("/save")
    //?
    .exchange()
    .block()
    .bodyToMono(Integer.class)
    .block();

【问题讨论】:

    标签: java spring spring-webflux


    【解决方案1】:

    在创建 URI 时存在许多编码挑战。为了在编码部分保持正确的同时获得更大的灵活性,WebClient 为 URI 提供了一个基于构建器的变体:

    WebClient.create().get()
        .uri(builder -> builder.scheme("http")
                        .host("example.org").path("save")
                        .queryParam("name", "spring-framework")
                        .build())
        .retrieve()
        .bodyToMono(String.class);
    

    【讨论】:

    • 是的,同样适用于 POST 请求
    【解决方案2】:

    发件人:https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/

    在配置类中你可以定义主机:

    @Bean(name = "providerWebClient")
    WebClient providerWebClient(@Value("${external-rest.provider.base-url}") String providerBaseUrl) {
    return WebClient.builder().baseUrl(providerBaseUrl)
        .clientConnector(clientConnector()).build();
    }
    

    然后就可以使用 WebClient 实例了:

    @Qualifier("providerWebClient")
    private final WebClient webClient;
    
    webClient.get()
            .uri(uriBuilder -> uriBuilder.path("/provider/repos")
                    .queryParam("sort", "updated")
                    .queryParam("direction", "desc")
                    .build())
            .header("Authorization", "Basic " + Base64Utils
                    .encodeToString((username + ":" + token).getBytes(UTF_8)))
            .retrieve()
            .bodyToFlux(GithubRepo.class);
    

    【讨论】:

    • 主机呢?你在哪里指定的?
    • @MikayilAbdullayev 我刚刚编辑了答案以添加配置的那部分。
    【解决方案3】:

    假设您已经创建了 WebClient 实例并使用 baseUrl 对其进行了配置。

    URI 路径组件

    this.webClient.get()
          .uri("/products")
          .retrieve();
    

    结果:/products

    this.webClient.get()
          .uri(uriBuilder - > uriBuilder
            .path("/products/{id}")
            .build(2))
          .retrieve();
            
    

    结果:/products/2

     this.webClient.get()
          .uri(uriBuilder - > uriBuilder
            .path("/products/{id}/attributes/{attributeId}")
            .build(2, 13))
          .retrieve();
    

    结果:/products/2/attributes/13

    URI查询参数

    this.webClient.get()
      .uri(uriBuilder - > uriBuilder
        .path("/peoples/")
        .queryParam("name", "Charlei")
        .queryParam("job", "Plumber")
        .build())
      .retrieve();
    

    结果:

    /peoples/?name=Charlei/job=Plumber
    

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2012-10-01
      • 2020-07-12
      • 2020-09-02
      • 1970-01-01
      • 2018-12-09
      • 2021-02-24
      • 2020-04-14
      • 2019-06-04
      相关资源
      最近更新 更多