问题描述
我正在尝试将JSON对象发布到接受以下格式数据的API端点
I am trying to POST a JSON object to an API endpoint which accepts the data in below format
{
"names": [
"name1",
"name2",
"name3"
]
}
我的发布方法如下
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);
}
当我调用post方法时出现此错误
When I call the post method I get this error
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request
我打印出了jsonObject
,并尝试通过邮递员发布它,
I printed out the jsonObject
and tried to post it via Postman, it worked.
我在这里想念的重点是什么?
What is the point that I am missing here?
任何帮助将不胜感激.
推荐答案
在您的情况下,直接通过RestTemplate发布JsonObject不起作用的原因是RestTemplate使用的是Jackson序列化器-而不是toString方法.序列化程序将获取类的内部结构,并将其转换为json表示形式,其中toString()方法为您提供了所需的json数据.
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"}
这不是您期望的结构,但这部分是JsonObject在内部存储json结构的方式. (捕获类型信息等).
This is not the structure you were expecting but it is partly how JsonObject stores your json structure internally. (capturing type information etc).
但是,当您调用toString()时,JsonObject会给您您所期望的内容(即不包含所有元数据的json表示形式).
However, when you call toString(), the JsonObject gives you what you were expecting (i.e. a json representation without all the metadata).
因此,简而言之,您认为发送的内容与实际发送的内容有所不同.您遇到的400错误可能是因为您正在调用的端点拒绝了数据的实际格式.
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.
您可以通过使用拦截器调试RestTemplate进行的实际调用来亲自查看.或者,让您的客户致电回显服务以查看有效负载.
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.
这篇关于通过Spring Boot中的RestTemplate POST JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!