如何使用TLSv1设置RestTemplate调用

时间:2019-07-09 06:52:27

标签: java ssl java-8 resttemplate tls1.0

我必须使应用程序基于java8,使其可以将API与仅接受TLSv1的服务器连接。

我尝试一下,但是没有用。

    public static RestTemplate restTemplate() throws Exception {
        DefaultResourceLoader loader = new DefaultResourceLoader();

        String keystorePassword = "password";
        KeyStore keyStore = new KeyStoreFactoryBean(
                new ClassPathResource("classpath:static/p12.p12"),
                "PKCS12",
                keystorePassword
        ).newInstance();

        KeyStore trustStore = new KeyStoreFactoryBean(
                new ClassPathResource("classpath:static/jks.jks"),
                "JKS",
                "pasword"
        ).newInstance();

        SSLContext sslContext = SSLContexts.custom()
                .setProtocol("TLSv1") // Set TLSv1 here.
                .loadKeyMaterial(keyStore, keystorePassword.toCharArray())
                .loadTrustMaterial(trustStore, (x509Certificates, s) -> false)
                .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();

        BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(connectionManager)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        restTemplate.setErrorHandler(new RestTemplateErrorHandler());

        return restTemplate;
    }

这是一个错误。

http-nio-8080-exec-1, READ: TLSv1 Alert, length = 2
http-nio-8080-exec-1, RECV TLSv1.2 ALERT:  fatal, handshake_failure
http-nio-8080-exec-1, called closeSocket()
http-nio-8080-exec-1, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://example.com/something/": Received fatal alert: handshake_failure; nested exception is javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

0 个答案:

没有答案