修改自:http://blog.joylau.cn/2020/10/19/SpringBoot-RestTemplate-SSL/
解決辦法是寫一個@Configuration配置類,里面添加代碼:
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; @Bean public RestTemplate restTemplate(){ return new RestTemplateBuilder.build(); } /** * HTTPS RestTemplate */ @Bean public RestTemplate httpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setSSLSocketFactory(sslConnectionSocketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); requestFactory.setConnectTimeout((int)Duration.ofSeconds(5).toMillis()); return new RestTemplate(requestFactory); }
然后用的地方由原來的:
@Resource private RestTemplate restTemplate;
改成:
@Resource private RestTemplate httpsRestTemplate;
即可;