'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();
Solution 1:[1]
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);
Solution 2:[2]
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);
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kamwo |
| Solution 2 | |
| Solution 3 | TuGordoBello |
