RestTemplate发送请求,配置HTTPS请求忽略SSL证书

本文档详细介绍了在使用Spring RestTemplate发送HTTPS请求时遇到的证书验证问题,以及如何通过配置RestTemplate来忽略证书认证。首先,解释了出现`sun.security.validator.ValidatorException`错误的原因,指出了解决方案:一是配置RestTemplate忽略证书,二是下载并使用证书。接着,提供了所需导入的Apache HttpClient相关jar包,并展示了如何在Spring配置类中创建一个忽略证书的RestTemplate实例。最后,给出了参考博客链接以供深入学习。

一、问题的出现

最近在使用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;
    }
}

四、参考博客

RestTemplate Https请求忽略SSL证书_CarsonJava的博客-优快云博客_resttemplate忽略ssl证书@Configurationpublic class RestTemplateProxy { @Autowired private RestTemplate restTemplate; @Autowired @LoadBalanced private RestTemplate lbRestTemplate; @Autowired private AsyncRestTemplate asyncRestTemplate; @Autowi.https://blog.youkuaiyun.com/Carson073/article/details/107556662

如果你想在使用 RestTemplate 发送 POST 请求忽略证书,可以通过创建一个自定义的 RestTemplate 来实现。下面是一个示例代码: ```java import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class CustomRestTemplate extends RestTemplate { public CustomRestTemplate() { super(); setRequestFactory(new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); ((HttpsURLConnection) connection).setSSLSocketFactory(createSslSocketFactory()); } super.prepareConnection(connection, httpMethod); } }); } private static SSLSocketFactory createSslSocketFactory() { SSLSocketFactory sslSocketFactory = null; try { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return sslSocketFactory; } } ``` 在上面的代码中,我们创建了一个自定义的 RestTemplate,其中重写了 prepareConnection 方法,在发送 HTTPS 请求忽略证书。 使用这个自定义的 RestTemplate,只需要在代码中实例化它并使用即可: ```java CustomRestTemplate restTemplate = new CustomRestTemplate(); String result = restTemplate.postForObject(url, request, String.class); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值