web項目難免會用上Http請求有些地址沒有安全證書,Java默認是不能訪問這些地址的,一般的方法是忽略安全證書,網上查了一圈,看似很多資料,但我卻沒找到一個拿來就可以用的,最後整合了網上的信息,弄出來一個可用的,我也不確定我這個是不是通用的, 畢竟其實都還不太清楚原理。只是記錄一下:
//忽略安全證書認證的連接方式
private static RestTemplate ignoreSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}