RestTemplate 发送json格式的http请求

 主方法:ResponseEntity 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 aa = new HashMap();
aa.put("id", "123");
Student student = new Student();
student.setAa("大智慧aa");
student.setBb("bb");
student.setCc("cc");
RestTemplate restTemplate = new RestTemplate();
HttpEntity entity = new HttpEntity(student, headers);
// ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Student.class, aa);
ResponseEntity 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());

你可能感兴趣的:(java编程)