POST JSON Object via RestTemplate in Spring Boot

孤街浪徒 提交于 2019-12-10 22:28:28

问题


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.


回答1:


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.




回答2:


Create a JSONArray object using names and then set the json array in jsonObject.put("names", jsonArrayObject);




回答3:


You need not do all this , i guess

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

}

Can be easily done using POJO

create a POJO,

   @Entity
    class Name{
   @JsonProperty
    private String name1;
    getter(); setter();}

create your post method where you pass the exact object as in pojo

@PostMapping("/RESTENDPOINT")
public String post(@RequestBody Name name) {
    return repository.save(name); // your logic
}



回答4:


refer to baeldung.com,rest-template sample.You can user HttpEntity,T not JSONObject but POJO type,LIKE:

HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
ReturnType result = restTemplate.postForObject(fooResourceUrl, request, ReturnType.class);

HttEntity is Represents an HTTP request or response entity, consisting of headers and body. Typically used in combination with RestTemplate



来源:https://stackoverflow.com/questions/54383950/post-json-object-via-resttemplate-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!