springboot 使用restTemplate 发送https请求 忽略ssl证书

导读:本篇文章讲解 springboot 使用restTemplate 发送https请求 忽略ssl证书,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

最近在写接口的时候给对方回推数据,发送https请求的时候遇到这么个报错:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetHTTPS经由超文本传输协议(HTTP)进行通信,但利用SSL/TLS来加密数据包,这里遇到的问题就是这个安全证书缺少产生的,所以,为了解决这个问题,一般有良好总方法,第一种是将对方网站的证书提前下到本地导入,这里的场景不大适合这个方式,所以采用第二种方式,忽略ssl证书的方法:

具体步骤大致有3步,首先添加一个RestTemplateConfig配置文件,源码如下:

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>Description: restTemplate配置类</p >
 * <p>Copyright: Copyright (c) 2022</p >
 *
 * @author zhunter
 * @version 1.0
 * @date 2022-09-07-16:32
 */

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
    {
        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类:

RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());

第三步便可以将发送信息写进代码中发送请求了

/**
     * 调用第三方服务器接口
     * 传入JSONObject表示post请求
     * 不传表示get请求
     * @param url 路由
     * @param jsonObject 参数
     * @param method 方法
     * @return
     */
    public static JSONObject forwardAlgorithm(String url,JSONObject jsonObject,HttpMethod method) throws Exception{
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        //此处加编码格式转换
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8);
        HttpEntity httpEntity = new HttpEntity(jsonObject, httpHeaders);
        //访问第三方服务器
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, httpEntity, String.class);
        return JSONObject.parseObject(exchange.getBody(),JSONObject.class);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/106554.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!