resttemplate http json
时间: 2023-09-24 07:10:47 浏览: 97
RestTemplate是Spring框架提供的一个用于进行HTTP通信的客户端工具。它支持各种HTTP方法,包括GET、POST、PUT、DELETE等,并且可以与服务器交换数据,例如JSON。
使用RestTemplate发送HTTP请求并处理JSON响应的示例代码如下:
```
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 请求参数
Map<String, String> params = new HashMap<>();
params.put("id", "123");
// 请求体
Student student = new Student();
student.setAa("aa");
student.setBb("bb");
student.setCc("cc");
// 创建HttpEntity对象以封装请求体和请求头
HttpEntity<Student> entity = new HttpEntity<>(student, headers);
// 发送POST请求,并获取响应
String url = "http://localhost:8080/test/testadd/{id}";
ResponseEntity<Student> responseEntity = restTemplate.postForEntity(url, entity, Student.class, params);
// 解析响应
Student studentResult = responseEntity.getBody();
System.out.println(studentResult.getAa());
System.out.println(studentResult.getBb());
System.out.println(studentResult.getCc());
```
在这个示例中,我们首先创建了一个RestTemplate实例,然后设置了请求头和参数。接下来,我们创建了一个包含请求体和请求头的HttpEntity对象,并使用postForEntity方法发送POST请求。最后,我们从响应中获取Student对象,并打印出其中的属性值。
希望这个示例能够帮助您理解如何使用RestTemplate发送HTTP请求并处理JSON响应。
阅读全文
相关推荐

















