【Java】 如何使用RestTemplate傳送HTTPS請求(忽略證書)
阿新 • • 發佈:2022-05-24
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.程式碼實現
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(); }