How to post request with spring boot web-client for Form data for content type application/x-www-form-urlencoded
Asked Answered
T

2

34

How To use spring boot webclient for posting request with content type application/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?

Transfinite answered 17/1, 2020 at 17:28 Comment(0)
T
79

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();
    
Transfinite answered 17/1, 2020 at 17:28 Comment(2)
That doesnt work for me. I get the following exception: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.web.reactive.function.BodyInserters$DefaultFormInserterAntitragus
Nevermind. I used bodyValue instead of body. It works!Antitragus
W
31

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.

Wang answered 4/9, 2020 at 18:25 Comment(2)
This will block the call, so it will wait until the request is finished and returnKeek
instead of .body(BodyInserters.fromFormData(formData)) should be .body(formData)Egalitarian

© 2022 - 2024 — McMap. All rights reserved.