How to disable SSL certificate checking with Spring RestTemplate?

后端 未结 9 1227
余生分开走
余生分开走 2020-11-29 18:11

I am trying to write an integration test where our test launches an embedded HTTPS server using Simple. I created a self-signed certificate using keytool and am able to acce

9条回答
  •  清歌不尽
    2020-11-29 18:42

    @Bean(name = "restTemplateByPassSSL")
    public RestTemplate restTemplateByPassSSL()
            throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
    
        return new RestTemplate(requestFactory);
    }
    

提交回复
热议问题