restTemplate访问https

maven

        
            org.apache.httpcomponents
            httpclient
            4.5.3
        

配置


@Configuration
public class RestConfig {

    @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;
    }
}

测试

String url=address+"/apis/elevator/wx/number";
Map stringObjectMap=new HashMap<>();
stringObjectMap.put("number",number);
restTemplate.getForObject(url+"?number={number}", Object.class,stringObjectMap);

注意:这是一种规避https 安全的做法,达到可调用的效果,失去信息加密的安全意义

你可能感兴趣的:(Java)