28

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.

Avv
  • 555
  • 1
  • 10
  • 18

3 Answers3

32

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

Brian Clozel
  • 56,583
  • 15
  • 167
  • 176
22

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).

Hamza Belmellouki
  • 2,516
  • 1
  • 18
  • 39
1

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;
}
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – MD. RAKIB HASAN Nov 29 '21 at 09:08