Issue
MultiValueMap<String, String> body_data = new LinkedMultiValueMap();
body_data.add("param1", {param1});
...
WebClient webClient = WebClient.builder().baseUrl(api_url+request_url)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.build();
String result = webClient.post().contentType(MediaType.APPLICATION_FORM_URLENCODED)
.bodyValue(BodyInserters.fromFormData(body_data)).retrieve().bodyToMono(String.class).block();
and it returns
org.springframework.web.reactive.function.client.WebClientRequestException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.web.reactive.function.BodyInserters$DefaultFormInserter; nested exception is org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.web.reactive.function.BodyInserters$DefaultFormInserter
Any suggestion for this? content-type should be application/x-www-form-urlencoded.
Solution
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();
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();
Answered By - Akshay Jain
Answer Checked By - Gilberto Lyons (JavaFixing Admin)