RestTemplate是Spring提供的用于同步HTTP请求的客户端工具,在Spring Boot中集成使用非常方便。以下是详细说明:
1. 基本配置
首先需要在项目中添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2. 创建RestTemplate实例
推荐使用配置类方式创建:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
3. 常用方法
GET请求
// 获取响应体 String result = restTemplate.getForObject(url, String.class); // 获取完整响应(包括状态码、头信息等) ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
POST请求
// 简单POST String result = restTemplate.postForObject(url, requestBody, String.class); // 带请求头的POST HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
4. 高级功能
设置超时时间
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(10)) .build(); }
添加拦截器
@Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add((request, body, execution) -> { request.getHeaders().add("Authorization", "Bearer token"); return execution.execute(request, body); }); return restTemplate; }
处理JSON
// 发送对象自动转为JSON User user = new User("John", 30); ResponseEntity<User> response = restTemplate.postForEntity(url, user, User.class); // 接收JSON自动转为对象 User result = restTemplate.getForObject(url, User.class);
5. 异常处理
RestTemplate默认会抛出以下异常:
HttpClientErrorException (4xx错误)
HttpServerErrorException (5xx错误)
ResourceAccessException (连接问题)
建议使用try-catch处理:
try { ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); // 处理响应 } catch (HttpClientErrorException e) { // 处理4xx错误 } catch (HttpServerErrorException e) { // 处理5xx错误 } catch (ResourceAccessException e) { // 处理连接问题 }
6. 替代方案
虽然RestTemplate仍然可用,但Spring官方推荐在Spring 5+中使用WebClient作为替代,它支持响应式编程和非阻塞IO。
7. 注意事项
RestTemplate是线程安全的,可以全局共享一个实例
对于复杂场景,考虑使用RestTemplateBuilder构建定制化的RestTemplate
生产环境中建议配置连接池和合理的超时时间。
0条评论
点击登录参与评论