【SpringBoot+RestTemplate】远程调用支持https,可切换httpclient或Okhttp

1、RestTemplate使用Okhttp调用https接口,SpringBoot配置如下所示:


    @Bean
    public RestTemplate restTemplate() {
        X509TrustManager trustManager;
        SSLContext sslContext;
        try {
            trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .hostnameVerifier((host, session) -> true)
                .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
                .connectTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(10L, TimeUnit.SECONDS)
                .writeTimeout(60L, TimeUnit.SECONDS)
                .build();
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(client);
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

2、RestTemplate使用HttpClient调用https接口,SpringBoot配置如下所示:

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
       try {
            TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
            requestFactory.setHttpClient(httpClient);
            requestFactory.setConnectionRequestTimeout(6000);
            requestFactory.setConnectTimeout(6000);
            requestFactory.setReadTimeout(10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
posted @ 2020-11-02 10:09  kevin_ying  阅读(2616)  评论(0编辑  收藏  举报
//系列教程