Spring RestTemplate: SSL handshake failure

后端 未结 2 1761
小蘑菇
小蘑菇 2020-12-31 20:45

I am trying to consume a restful ws with basic auth. I did not import any cert into my keystore. When I use chrome plugin Advance Rest client to test it (using

2条回答
  •  星月不相逢
    2020-12-31 21:10

    If you happen to be using Java 7 you need to explicitly tell Java to use TLSv1.2 protocol. Here is an example using Spring XML configuration.

    ***In any Spring bean (i.e. a controller)***
    
    import org.apache.http.client.HttpClient;
    import org.apache.http.ssl.SSLContexts;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.HttpClients;
    import javax.net.ssl.SSLContext;
    
    @Bean(name="client")
    public HttpClient make() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1.2", "TLSv1.1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        return HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
    }
    
    ***In XML configuration files***
    
    
        
    
    
        
    
    

    You could do the same without XML with something like this:

    RestTemplate restTemplate;
    
    public HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1.2", "TLSv1.1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        return HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
    }
    
    public void setUp() throws Exception {
        restTemplate = new RestTemplate(
                new HttpComponentsClientHttpRequestFactory(
                        getHttpClient()));
        ...
    }
    

提交回复
热议问题