【Java】 如何使用RestTemplate发送HTTPS请求(忽略证书)
1.RestTemplate默认是不支持HTTPS请求的,那么如果想使用RestTemplate发送一个HTTPS的请求 ,就需要对证书进行处理,这里记录一下一个可行的方法。
2.导包
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts;
3.Maven
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
4.代码实现
try { TrustStrategy acceptingTrustStrategy = (chain, authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClientBuilder clientBuilder = HttpClients.custom(); CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); this.restTemplate = new RestTemplate(requestFactory); } catch (Exception e) { e.printStackTrace(); }