Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST JSON Object via RestTemplate in Spring Boot

I am trying to POST a JSON object to an API endpoint which accepts the data in below format

{
    "names": [
        "name1",
        "name2",
        "name3"
    ]
}

And my post method is as below

public String post(List<String> names) {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    JSONObject jsonObject = new JSONObject();
    jsonObject .put("names", names);

    HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject , headers);

    return restTemplate.postForObject(Constants.URL, entity, String.class);
}

When I call the post method I get this error

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request

I printed out the jsonObject and tried to post it via Postman, it worked.

What is the point that I am missing here?

Any help would be appreciated.

like image 523
Tartar Avatar asked Mar 27 '26 06:03

Tartar


1 Answers

The reason posting the JsonObject directly via a RestTemplate doesn't work in your case is that the RestTemplate is using Jackson Serializer - not the toString method. The Serializer will pick up the internal structure of the class and turn this into a json representation, where as the toString() method gives you the json data that you're expecting.

In your case the internal representation when serialized will look something like this:

"names":{"chars":"namesstring","string":"namesstring","valueType":"STRING"}

This is not the structure you were expecting but it is partly how JsonObject stores your json structure internally. (capturing type information etc).

However, when you call toString(), the JsonObject gives you what you were expecting (i.e. a json representation without all the metadata).

So in short what you think you're sending and what you're actually sending are different. The 400 error you experience is probably because the endpoint you're calling is rejecting the actual format of the data.

You can see this for yourself by debugging the actual call that the RestTemplate makes by using an interceptor. Alternatively, have your client call an echo service to see the payload.

like image 75
Daniel Burrell Avatar answered Mar 29 '26 18:03

Daniel Burrell