spring框架提供的RestTemplate類可用於在應用中調用rest服務,它簡化了與http服務的通信方式,統一了RESTful的標准,封裝了http鏈接, 我們只需要傳入url及返回值類型即可。相較於之前常用的HttpClient,RestTemplate是一種更優雅的調用RESTful服務的方式。
RestTemplate默認依賴JDK提供http連接的能力(HttpURLConnection),如果有需要的話也可以通過setRequestFactory方法替換為例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
本篇介紹如何使用RestTemplate,以及在SpringBoot里面的配置和注入。
實現邏輯
RestTemplate包含以下幾個部分:
HttpMessageConverter 對象轉換器
ClientHttpRequestFactory 默認是JDK的HttpURLConnection
ResponseErrorHandler 異常處理
ClientHttpRequestInterceptor 請求攔截器
用一張圖可以很直觀的理解:

發送GET請求
發送POST請求
設置HTTP Header
捕獲異常
捕獲HttpServerErrorException
try { responseEntity = restTemplate.exchange(requestEntity, String.class); } catch (HttpServerErrorException e) {
自定義異常處理器
public class CustomErrorHandler extends DefaultResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException {
然后設置下異常處理器:
@Configuration public class RestClientConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomErrorHandler()); return restTemplate; } }
配置類
創建RestClientConfig
類,設置連接池大小、超時時間、重試機制等。配置如下:
@Configuration public class RestClientConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(clientHttpRequestFactory()); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); return restTemplate; } @Bean public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() { try { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); httpClientBuilder.setSSLContext(sslContext); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build();
注意,如果沒有apache的HttpClient類,需要在pom文件中添加:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
發送文件
MultiValueMap<String, Object> multiPartBody = new LinkedMultiValueMap<>(); multiPartBody.add("file", new ClassPathResource("/tmp/user.txt")); RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity .post(uri) .contentType(MediaType.MULTIPART_FORM_DATA) .body(multiPartBody);
下載文件
Service注入
@Service public class DeviceService { private static final Logger logger = LoggerFactory.getLogger(DeviceService.class); @Resource private RestTemplate restTemplate; }
實際使用例子
GitHub源碼
springboot-resttemplate