简体   繁体   English

在 Spring Boot 中通过 RestTemplate POST JSON 对象

[英]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我正在尝试将 JSON 对象发布到 API 端点,该端点接受以下格式的数据

{
    "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当我调用 post 方法时,我收到此错误

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

I printed out the jsonObject and tried to post it via Postman, it worked.我打印了jsonObject并尝试通过 Postman 发布它,它奏效了。

What is the point that I am missing here?我在这里想念的重点是什么?

Any help would be appreciated.任何帮助,将不胜感激。

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.通过 RestTemplate 直接发布 JsonObject 在您的情况下不起作用的原因是 RestTemplate 使用的是 Jackson Serializer - 而不是 toString 方法。 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. Serializer 将获取类的内部结构并将其转换为 json 表示,其中 toString() 方法为您提供您期望的 json 数据。

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.这不是您期望的结构,但这部分是 JsonObject 在内部存储您的 json 结构的方式。 (capturing type information etc). (捕获类型信息等)。

However, when you call toString(), the JsonObject gives you what you were expecting (ie a json representation without all the metadata).但是,当您调用 toString() 时,JsonObject 会为您提供您所期望的(即没有所有元数据的 json 表示)。

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.您遇到的 400 错误可能是因为您调用的端点拒绝了数据的实际格式。

You can see this for yourself by debugging the actual call that the RestTemplate makes by using an interceptor.您可以通过调试 RestTemplate 使用拦截器进行的实际调用来亲眼看到这一点。 Alternatively, have your client call an echo service to see the payload.或者,让您的客户端调用回显服务以查看有效负载。

使用names创建一个JSONArray对象,然后在jsonObject.put("names", jsonArrayObject);设置 json 数组jsonObject.put("names", jsonArrayObject);

refer to baeldung.com,rest-template sample .You can user HttpEntity,T not JSONObject but POJO type,LIKE:参考baeldung.com,rest-template 示例。你可以使用 HttpEntity,T 不是 JSONObject 而是 POJO 类型,比如:

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. HttEntity代表一个 HTTP 请求或响应实体,由 headers 和 body 组成。 Typically used in combination with RestTemplate通常与RestTemplate结合使用

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可以使用 POJO 轻松完成

create a POJO,创建一个POJO,

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

create your post method where you pass the exact object as in pojo创建您的 post 方法,您可以在其中传递与 pojo 中一样的确切对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM