在分布式系统开发中,服务间通信是常见需求。作为 Spring 框架的重要组件,RestTemplate 为开发者提供了简洁优雅的 HTTP 客户端解决方案。本文将从零开始讲解 RestTemplate 的核心用法,并附赠真实地图 API 对接案例。
一、环境准备
在 Spring Boot 项目中添加依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
通过配置类初始化 RestTemplate:
@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}
用的时候引入
@Autowiredprivate RestTemplate restTemplate;
二、基础用法全解析
1. GET 请求的三种姿势
方式一:路径参数(推荐)
String url = "https://api.example.com/users/{id}";
Map<String, Object> params = new HashMap<>();
params.put("id", 1001);User user = restTemplate.getForObject(url, User.class, params);
方式二:显式拼接参数
String url = "https://api.example.com/users?id=1001";
User user = restTemplate.getForObject(url, User.class);
方式三:URI 构造器
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://api.example.com/users").queryParam("name", "John").queryParam("age", 25);User user = restTemplate.getForObject(builder.toUriString(), User.class);
2. POST 请求深度实践
发送表单数据:
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("username", "admin");
formData.add("password", "123456");ResponseEntity<String> response = restTemplate.postForEntity("https://api.example.com/login", formData, String.class
);
提交 JSON 对象:
User newUser = new User("Alice", 28);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<User> request = new HttpEntity<>(newUser, headers);
User createdUser = restTemplate.postForObject("https://api.example.com/users", request, User.class
);
三、进阶配置技巧
1. 超时控制
@Bean
public RestTemplate customRestTemplate() {return new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(10)).build();
}
2. 拦截器实战
public class LoggingInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {logRequest(request, body);ClientHttpResponse response = execution.execute(request, body);logResponse(response);return response;}private void logRequest(HttpRequest request, byte[] body) {// 实现请求日志记录}private void logResponse(ClientHttpResponse response) {// 实现响应日志记录}
}
注册拦截器:
@Bean
public RestTemplate restTemplate() {RestTemplate restTemplate = new RestTemplate();restTemplate.setInterceptors(Collections.singletonList(new LoggingInterceptor()));return restTemplate;
}
四、实战案例:腾讯地图路线规划
@Service
public class MapService {@Value("${tencent.map.key}")private String apiKey;@Autowiredprivate RestTemplate restTemplate;public DrivingRoute calculateRoute(Location start, Location end) {String url = "https://apis.map.qq.com/ws/direction/v1/driving/"+ "?from={start}&to={end}&key={key}";Map<String, String> params = new HashMap<>();params.put("start", start.toString());params.put("end", end.toString());params.put("key", apiKey);ResponseEntity<MapResponse> response = restTemplate.getForEntity(url, MapResponse.class, params);if (response.getStatusCode() == HttpStatus.OK && response.getBody().getStatus() == 0) {return response.getBody().getResult().getRoutes().get(0);}throw new MapServiceException("路线规划失败");}
}
五、最佳实践建议
-
响应处理策略
- 使用
ResponseEntity<T>
获取完整响应信息 - 实现自定义错误处理器
ResponseErrorHandler
- 对于复杂 JSON 结构,建议定义完整的 DTO 类
- 使用
-
性能优化
- 启用连接池(推荐 Apache HttpClient)
- 合理设置超时时间
- 考虑异步调用(结合 AsyncRestTemplate)
-
安全防护
- 启用 HTTPS
- 敏感参数加密处理
- 配置请求频率限制
六、常见问题排查
问题1:收到 400 Bad Request
- 检查请求参数格式
- 确认 Content-Type 设置正确
- 验证请求体 JSON 结构
问题2:出现乱码
- 设置正确的字符编码
- 检查服务端和客户端的编码一致性
- 在 headers 中明确指定
charset=UTF-8
问题3:超时配置不生效
- 确认使用的 RestTemplate 实例正确
- 检查连接池配置是否覆盖超时设置
- 验证网络防火墙设置