使用RestTemplate访问HTTPS协议接口
转载:
package com.web.servelet; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.TrustStrategy; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.security.cert.X509Certificate; public class test2 { public static RestTemplate restTemplate1() throws Exception { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; // TrustStrategy acceptingTrustStrategy= new TrustStrategy() { // @Override // public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { // return 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; } }转载: package com.web.servelet; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.TrustStrategy; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.security.cert.X509Certificate; public class test2 { public static RestTemplate restTemplate1() throws Exception { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; // TrustStrategy acceptingTrustStrategy= new TrustStrategy() { // @Override // public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { // return 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; } }