1、RestTemplate 简介
RestTemplate 是 Spring 框架提供的一个用于同步(阻塞式)HTTP 请求的客户端工具类。它简化了与 HTTP 服务的通信过程,极大地方便了在 Java 应用中调用 RESTful Web 服务。
它的核心优势在于:
-
模板方法设计模式:封装了复杂的底层细节(如
HttpURLConnection)。 -
强大的消息转换器:自动将 Java 对象与 HTTP 请求/响应体(如 JSON, XML)进行序列化和反序列化。
-
集成 Spring 生态:与 Spring 的依赖注入、AOP 等无缝集成。
-
全面的 HTTP 方法支持:对 GET, POST, PUT, DELETE 等所有标准 HTTP 方法提供了对应的方法。
注意: 虽然 RestTemplate 在过去非常流行且被广泛使用,但 Spring 官方已宣布从 5.0 版本开始进入维护模式,不推荐在新项目中使用,并建议使用新的 WebClient 作为替代。
2、创建RestTemplate Bean
通过 @Configuration 类将其声明为一个 Bean。
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2、在 Service 或 Controller 中通过 @Autowired 注入:
@Service
public class MyService {
@Autowired
private RestTemplate restTemplate;
// ... 使用 restTemplate
}
3、核心方法与使用示例
下面使用 JSONPlaceholder 这个免费的测试 API 来演示
3.1 GET 请求 - 获取资源
1. getForObject - 获取响应体并将其转换为对象
// 将 JSON 响应直接转换为 String
String response = restTemplate.getForObject("https://jsonplaceholder.typicode.com/posts/1", String.class);
System.out.println(response);
// 定义对应的实体类
public class Post {
private Long userId;
private Long id;
private String title;
private String body;
// ... getters and setters
}
// 将 JSON 响应自动转换为 Post 对象
Post post = restTemplate.getForObject("https://jsonplaceholder.typicode.com/posts/1", Post.class);
System.out.println(post.getTitle());
2. getForEntity - 获取完整的 ResponseEntity(包含状态码、头信息等)
// 获取完整的响应实体
ResponseEntity<Post> responseEntity = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts/1", Post.class);
// 获取 HTTP 状态码
HttpStatus statusCode = responseEntity.getStatusCode(); // 200 OK
// 获取响应头
HttpHeaders headers = responseEntity.getHeaders();
// 获取响应体
Post postBody = responseEntity.getBody();
System.out.println("Status: " + statusCode);
System.out.println("Title: " + postBody.getTitle());
3. 使用 URI 变量(路径参数)
// 方式一:可变参数
Post post = restTemplate.getForObject(
"https://jsonplaceholder.typicode.com/posts/{id}",
Post.class,
1 // {id} 会被 1 替换
);
// 方式二:Map<String, ?>
Map<String, Object> map= new HashMap<>();
uriVariables.put("id", 1);
Post post = restTemplate.getForObject(
"https://jsonplaceholder.typicode.com/posts/{id}",
Post.class,
map
);
3.2 POST 请求 - 创建资源
1. postForObject - 发送请求并将响应体转换为对象
// 创建要发送的对象
Post newPost = new Post();
newPost.setUserId(1L);
newPost.setTitle("My New Post");
newPost.setBody("This is the body of my new post.");
// 发送 POST 请求,并将返回的 JSON 自动转换为 Post 对象
Post createdPost = restTemplate.postForObject(
"https://jsonplaceholder.typicode.com/posts",
newPost, // 请求体
Post.class // 响应体类型
);
System.out.println("Created Post ID: " + createdPost.getId()); // 模拟 API 会返回一个带 ID 的对象
2. postForEntity - 获取完整的 ResponseEntity
ResponseEntity<Post> responseEntity = restTemplate.postForEntity(
"https://jsonplaceholder.typicode.com/posts",
newPost,
Post.class
);
// 可以获取 Location 头(新创建资源的 URI)
String location = responseEntity.getHeaders().getFirst("Location");
Post createdPost = responseEntity.getBody();
3.3 PUT 请求 - 更新资源
使用 put 方法,它没有返回值。
Post updatedPost = new Post();
updatedPost.setUserId(1L);
updatedPost.setTitle("Updated Title");
updatedPost.setBody("Updated body content.");
// 发送 PUT 请求,更新 /posts/1 这个资源
restTemplate.put(
"https://jsonplaceholder.typicode.com/posts/{id}",
updatedPost, // 请求体
1 // URI 变量 {id}
);
3.4 DELETE 请求 - 删除资源
使用 delete 方法,它没有返回值。
// 删除 /posts/1 这个资源
restTemplate.delete("https://jsonplaceholder.typicode.com/posts/{id}", 1);
3.5 exchange - 通用且强大的方法
当需要更精细的控制(例如设置自定义请求头、使用非标准 HTTP 方法)时,可以使用 exchange 方法。
// 1. 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your-token");
headers.setContentType(MediaType.APPLICATION_JSON);
// 2. 将请求头和体封装到 HttpEntity 中
HttpEntity<Post> requestEntity = new HttpEntity<>(newPost, headers);
// 3. 使用 exchange 发送 POST 请求
ResponseEntity<Post> response = restTemplate.exchange(
"https://jsonplaceholder.typicode.com/posts",
HttpMethod.POST, // 指定 HTTP 方法
requestEntity, // 包含头和体的请求实体
Post.class // 期望的响应类型
);
Post result = response.getBody();
4. 配置与自定义
默认的 RestTemplate 可能不满足所有需求,我们可以通过 RestTemplateBuilder 来轻松定制。
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
// 设置连接超时和读取超时
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(5))
// 设置默认的 Basic Auth
.basicAuthentication("username", "password")
// 添加自定义的拦截器(例如统一加请求头、记录日志)
.interceptors(new MyCustomInterceptor())
// 设置自定义的消息转换器列表
// .messageConverters(new MappingJackson2HttpMessageConverter())
.build();
}
5、拓展:JSONPlaceholder
1、JSONPlaceholder 是一个免费的在线假 REST API 服务,专门为需要虚拟数据进行测试、原型制作、演示或教学的用户设计。它不需要注册,也不需要 API 密钥,开箱即用。
可以把它理解为一个 "API 模拟器" 或 "虚拟后端",当你的前端或移动端应用需要与后端 API 交互,但真实的后端 API 尚未开发完成时,JSONPlaceholder 就是一个完美的替代品。
2、JSONPlaceholder 是一个不可或缺的开发者工具。它以其极致的简单性和实用性,成为了无数开发者学习、测试和原型开发过程中的"瑞士军刀"。当你需要快速验证一个与 API 交互的想法时,它应该是你的首选工具。
798

被折叠的 条评论
为什么被折叠?



