RestTemplate 发送json格式的http请求

时间:2021-03-25 21:12:25

 主方法:ResponseEntity<Student> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Student.class, aa);

说明:

0. url 请求路径;

1. exchange可以发送HttpMethod.POST,DELE,GET,PUT请求;

2. entity包含请求的对象和消息头;

3. Student.class返回的信息的对象;

4. aa是url中出现的路径变量。



示例:

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
String url = "http://localhost:8080/test/testadd/{id}";
Map<String, String> aa = new HashMap<String, String>();
aa.put("id", "123");
Student student = new Student();
student.setAa("大智慧aa");
student.setBb("bb");
student.setCc("cc");
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Student> entity = new HttpEntity<Student>(student, headers);
// ResponseEntity<Student> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Student.class, aa);
ResponseEntity<Student> responseEntity = restTemplate.postForEntity(url, entity, Student.class, aa);
Student studentResult = responseEntity.getBody();
System.out.println(studentResult.getAa());
System.out.println(studentResult.getBb());
System.out.println(studentResult.getCc());