1、后端的接口定义
@PostMapping(value = "/entity")
public User insertUserEntity(@RequestBody User user) {
user.setAid(100);
user.setName("LiLie");
}
2、调用后端接口
public static User insertUser() {
// 请求头
HttpHeaders headers = new HttpHeaders();
// 设置请求内容为JSON类型,这里后面默认是utf-8的所以不用特意选择utf-8
headers.setContentType(MediaType.APPLICATION_JSON);
//headers.setch
User userRequest = new User();
userRequest.setAname("Lili");
// 创建请求实体对象
HttpEntity<User> request = new HttpEntity<>(userRequest, headers);
RestTemplate restTmpl = new RestTemplate();
// 请求时传递请求实体对象,并返回回填id的用户
User user = restTmpl.postForObject("http://localhost:8080/myspringdemo/user/insert", request, User.class);
System.out.println(user.getAid());
return user;
}