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

Niraj Sonawane picture Niraj Sonawane · Jan 17, 2020 · Viewed 10.5k times · Source

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?

Answer

Niraj Sonawane picture Niraj Sonawane · Jan 17, 2020

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