How to disable SSL certificate checking with Spring RestTemplate?

后端 未结 9 1230
余生分开走
余生分开走 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 19:02

    For the sake of other developers who finds this question and need another solution that fits not only for unit-tests:

    I've found this on a blog (not my solution! Credit to the blog's owner).

    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();
    
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(csf)
            .build();
    
    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();
    
    requestFactory.setHttpClient(httpClient);
    
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    

提交回复
热议问题