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

最近在写接口的时候给对方回推数据,发送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);
    }
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在使用 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、付费专栏及课程。

余额充值