RestTemplate发送请求,配置HTTPS请求忽略SSL证书
一、问题的出现
最近在使用RestTemplate发送请求的时候,出现了这样的一个问题:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
通过搜索原因,发现是RestTemplate发送该https请求,需要附带上证书去请求(目前看应该是客户端单向的要求,不带也行,只需客户端配置,服务端不强求)。
解决方案:
1、在使用RestTemplate发送请求的时候,如果发送的是https请求,并且该请求需要证书认证时,那么就通过配置RestTemplate,忽略https证书认证,直接发送请求。
2、可以把证书下载下来,这种操作比较复杂,这里不做这种方法的描述。
二、前期准备
该项目是maven项目,由于配置RestTemplate的部分使用类来自于apache的一些jar包,在开始配置前先导入如下jar包:
<!--定制请求跳过ssl证书验证--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> </dependency> <!--定制请求跳过ssl证书验证-->
jar包版本根据需求选择。
三、RestTemplate配置
/** * RestTemplate配置类 */ @Slf4j @Configuration public class RestTemplateConfig { /** * 忽略Https证书认证RestTemplate * @return unSSLRestTemplate */ @Bean("unSSLRestTemplate") public RestTemplate unSSLRestTemplate() throws UnSSLRestTemplateCreateException { try{ RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory()); return restTemplate; }catch (Exception e){ log.error(e.getMessage()); throw new UnSSLRestTemplateCreateException("unSSLRestTemplate bean创建失败,原因为:" + e.getMessage()); } } /** * 通过该工厂类创建的RestTemplate发送请求时,可忽略https证书认证 * @return 工厂 */ private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws Exception{ TrustStrategy acceptingTrustStrategy = ((x509Certificates, authType) -> true); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(connectionSocketFactory); CloseableHttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); return factory; } }
四、参考博客
上一篇:
IDEA上Java项目控制台中文乱码