RestTemplate 添加ssl证书
时间: 2023-07-11 17:51:40 浏览: 49
要为 RestTemplate 添加 SSL 证书,需要以下步骤:
1. 将证书文件添加到项目中,建议将证书放在 resources 目录下。
2. 创建 SSLContext 对象,并加载证书文件。
```
// 加载证书文件
Resource resource = new ClassPathResource("ssl.crt");
InputStream inputStream = resource.getInputStream();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
inputStream.close();
// 创建 KeyStore,存储证书
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry("alias", certificate);
// 创建 TrustManagerFactory,并初始化 KeyStore
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// 创建 SSLContext,并初始化 TrustManager
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
```
3. 使用 HttpClientBuilder 创建 HttpClient,设置 SSLContext。
```
// 创建 HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置 SSLContext
httpClientBuilder.setSSLContext(sslContext);
// 创建 CloseableHttpClient
CloseableHttpClient httpClient = httpClientBuilder.build();
```
4. 创建 HttpComponentsClientHttpRequestFactory 对象,并设置 HttpClient。
```
// 创建 HttpComponentsClientHttpRequestFactory
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
// 设置 HttpClient
requestFactory.setHttpClient(httpClient);
```
5. 创建 RestTemplate 对象,并设置 HttpComponentsClientHttpRequestFactory。
```
// 创建 RestTemplate
RestTemplate restTemplate = new RestTemplate(requestFactory);
```
这样,就可以使用带有 SSL 证书的 RestTemplate 发送 HTTPS 请求了。