How to post request with spring boot web-client for Form data for content type application/x-www-form-urlencoded
20,722
Solution 1
We can use BodyInserters.fromFormData
for this purpose
webClient client = WebClient.builder()
.baseUrl("SOME-BASE-URL")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.build();
return client.post()
.uri("SOME-URI)
.body(BodyInserters.fromFormData("username", "SOME-USERNAME")
.with("password", "SONE-PASSWORD"))
.retrieve()
.bodyToFlux(SomeClass.class)
.onErrorMap(e -> new MyException("messahe",e))
.blockLast();
Solution 2
In another form:
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("username", "XXXX");
formData.add("password", "XXXX");
String response = WebClient.create()
.post()
.uri("URL")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.exchange()
.block()
.bodyToMono(String.class)
.block();
In my humble opinion, for simple request, REST Assured is easier to use.
Author by
Niraj Sonawane
I love to follow latest trends and Best Practices in software engineering. My Day to day job is to write Clean, Elegant and Scalable Code.
Updated on October 13, 2021Comments
-
Niraj Sonawane over 2 years
How To use spring boot
webclient
for posting request with content typeapplication/x-www-form-urlencoded
sample curl request with content type `application/x-www-form-urlencoded'--header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'username=XXXX' \ --data-urlencode 'password=XXXX'
How Can i send same request using webclient?