Java使用Https请求忽略SSL认证

  • Post author:
  • Post category:java


  • 前言

最近在负责一个对接第三方服务的事情,在对接期间,因为第三方服务为https的请求,众所周知,请求https请求会使用本地的证书公钥去访问服务SSL证书,应我本地并没有对应的SSL证书,所以请求不到服务,请求接口时报如下错误。翻阅资源发现是可以 忽略SSL认证的。

 unable to find valid certification path to requested target

​​​​​​​

一、 编写RestTemplate 配置类

@Configuration
public class RestTemplateConfig {

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

    /**
     * 忽略SSL证书
     * @return
     */
    private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        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;
    }

}

二 、编写测试类

@SpringBootTest
public class IgnoreSSLTest {

    @Autowired
    private RestTemplate restTemplate;

    private String url = "https://xxx.xxxx";
    @Test
    public void test() {
        //使用restTemplate实现服务调用
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class);
        System.out.println("返回值为:" + responseEntity);
    }
}

测试结果查看是否成功请求接口,并忽略SSL证书。

当然还有安装证书等很多方法。



版权声明:本文为xiaozhang_man原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。