restTemplate 发送JSON
restTemplate 发送JSON
1. 使用 postForEntity
String url="http://www.test.com/api/getUser";
User user= new User();
user.setName("zhangsan");
String s = JSON.toJSONString(user);
// 要点1: 这三句设置header非常重要
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<String>(s, headers);
try {
// 要点2:这里要发送包含header的request,不要直接发对象的json报文
ResponseEntity<User> mapResponseEntity= restTemplate.postForEntity(url, request, User.class);
user u= mapResponseEntity.getBody()
}catch (Exception e){
logger.error("异常了",e);
}