How to send request body in spring-boot web client?

Viewed 41293

I'm facing some problem while sending request body in spring boot web client. Trying to send body like below:

val body = "{\n" +
            "\"email\":\"test@mail.com\",\n" +
            "\"id\":1\n" +
            "}"
val response = webClient.post()
    .uri( "test_uri" )
    .accept(MediaType.APPLICATION_JSON)
    .body(BodyInserters.fromObject(body))
    .exchange()
    .block()

Its not working. Request body should be in JSON format. Please let me know where I'm doing wrong.

3 Answers

You're not setting the "Content-Type" request header, so you need to append .contentType(MediaType.APPLICATION_JSON) to the request building part.

The above answer is correct: Adding application/json in your Content-Type header solves the isssue. Though, In this answer, I'd like to mention that BodyInserters.fromObject(body) is deprecated. As of Spring Framework 5.2, it is recommended to use BodyInserters.fromValue(body).

You can try like following:

public String wcPost(){

    Map<String, String> bodyMap = new HashMap();
    bodyMap.put("key1","value1");
 

    WebClient client = WebClient.builder()
            .baseUrl("domainURL")
            .build();


    String responseSpec = client.post()
            .uri("URI")
            .headers(h -> h.setBearerAuth("token if any"))
            .body(BodyInserters.fromValue(bodyMap))
            .exchange()
            .flatMap(clientResponse -> {
                if (clientResponse.statusCode().is5xxServerError()) {
                    clientResponse.body((clientHttpResponse, context) -> {
                        return clientHttpResponse.getBody();
                    });
                    return clientResponse.bodyToMono(String.class);
                }
                else
                    return clientResponse.bodyToMono(String.class);
            })
            .block();

    return responseSpec;
}
Related