在分布式系統開發中,服務間通信是常見需求。作為 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 實例正確
- 檢查連接池配置是否覆蓋超時設置
- 驗證網絡防火墻設置