什么是RestTemplate
RestTemplate 是 Spring Framework 提供的用于简化 HTTP 请求的客户端工具类。它封装了很多常见的 HTTP 操作,例如发送 GET、POST、PUT、DELETE 等请求,并且支持处理请求参数、请求头、响应处理等功能。
RestTemplate 的简单示例:
引入依赖:在 Maven 或 Gradle 构建文件中添加 RestTemplate 的依赖。
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradle:
groovy
implementation 'org.springframework.boot:spring-boot-starter-web'
创建 RestTemplate 实例:
RestTemplate restTemplate = new RestTemplate();
发送 GET 请求:
String url = "http://api.example.com/data";
String response = restTemplate.getForObject(url, String.class);
发送 POST 请求:
String url = "http://api.example.com/data";
String requestBody = "request body";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
发送 PUT 请求:
String url = "http://api.example.com/data";
String requestBody = "request body";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
restTemplate.put(url, entity);
发送 DELETE 请求:
String url = "http://api.example.com/data/{id}";
restTemplate.delete(url, 1);
这只是 RestTemplate 的一些基本用法示例,它还支持更多高级功能,如请求参数映射、拦截器、错误处理等。你可以根据具体的业务需求和接口文档来选择并使用适当的方法。
需要注意的是,从 Spring 5.0 版本开始,Spring 推荐使用 WebClient 替代 RestTemplate 来进行异步、非阻塞的 HTTP 请求操作。