Zufar Muhamadeev
Zufar Muhamadeev

Reputation: 3212

How to create request with parameters with webflux Webclient?

At backend side I have REST controller with POST method:

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

How can I create request using WebClient with request parameter?

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

Upvotes: 18

Views: 41532

Answers (3)

Alexis Gamarra
Alexis Gamarra

Reputation: 4412

From: https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/

In configuration class you can define the host:

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

Then you can use the WebClient instace:

@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);

Upvotes: 10

user10840312
user10840312

Reputation:

Assuming that you already created your WebClient instance and configured it with baseUrl.

URI Path Component

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

result: /products

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

result: /products/2

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

result: /products/2/attributes/13

URI Query Parameters

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

result:

/peoples/?name=Charlei/job=Plumber

Upvotes: 7

Brian Clozel
Brian Clozel

Reputation: 59056

There are many encoding challenges when it comes to creating URIs. For more flexibility while still being right on the encoding part, WebClient provides a builder-based variant for the URI:

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

Upvotes: 30

Related Questions