美文网首页java学习
restTemplate访问https

restTemplate访问https

作者: go4it | 来源:发表于2017-08-20 13:52 被阅读2870次

    本文简述一下怎么使用restTemplate来访问https。

    maven

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
    

    这里使用httpclient的factory

    配置

        @Bean
        public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
            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);
            return restTemplate;
        }
    

    验证

        @Test
        public void testHttps(){
            String url = "https://free-api.heweather.com/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";
            String resp = restTemplate.getForObject(url, String.class);
            System.out.println(resp);
        }
    

    doc

    相关文章

      网友评论

        本文标题:restTemplate访问https

        本文链接:https://www.haomeiwen.com/subject/ylsfdxtx.html