我正在尝试使用RestTemplate在json对象中发布一个数组
{
"update": {
"name": "xyz",
"id": "C2",
"Description": "aaaaaa",
"members": ["abc", "xyz"]
}
}
这是我的PostMapping控制器
@PostMapping(value = "/update")
public Update update(@RequestBody Update update) {
String url = "";
HttpHeaders headers = createHttpHeaders("username", "passowrd");
JSONObject jsonObject = new JSONObject();
jsonObject.put("update", update);
HttpEntity<JSONObject> request = new HttpEntity<>(jsonObject, headers);
ResponseEntity<Update> update = restTemplate.exchange(url, HttpMethod.POST,request, Update.class);
return update.getBody();
}
这是我的POJO
public class Update {
private String name;
private String id;
private String Descripion;
private List<String> members;
}
我得到了500美元
{
"timestamp": "2020-03-13T06:31:21.822+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No HttpMessageConverter for org.json.JSONObject and content type \"application/json\""
}
发布于 2020-03-13 15:56:07
尝试使用Json Message Converter配置您的RestTemplate。
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
你可以参考这篇博客来获得详细的解释。
https://www.baeldung.com/spring-httpmessageconverter-rest
然后执行rest调用,因为below.You将不再需要显式创建Json对象。
String url = "";
HttpEntity<Update> request = new HttpEntity<>(update, headers);
ResponseEntity<Update> firewallGroupUpdate = restTemplate.exchange(url, HttpMethod.POST, request, Update.class);
return firewallGroupUpdate.getBody();
发布于 2020-03-31 13:05:22
已将resttemplate.exchange更改为resttemplate.postForObject。并且还将方法更改为返回字符串。
public String groupUpdate(@RequestBody String groupUpdate) {
String url = "";
HttpHeaders headers = createHeaders("username","password");
headers.setContentType(MediaType.APPLICATION_JSON);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<String> requestEntity = new HttpEntity<String>(groupUpdate, headers);
String response = restTemplate.postForObject(url,requestEntity,String.class);
return response;
}
https://stackoverflow.com/questions/60665986
复制相似问题