屏蔽HTTPS證書校驗
—————————————————————————————————————————
背景需求:解決下面的錯誤:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
經查詢,需要繞過HTTPS證書校驗岂傲。
類似rest-client客戶端的SSL項的兩個設置:
1颊糜、Trust-self-signed certificate扬跋? 勾選
2拌消、Hostname verifier 選擇Allow All
下面代碼可以繞過HTTPS的證書校驗:
public static CloseableHttpClient createHttpsClient() throws NoSuchAlgorithmException, KeyManagementException
{
X509TrustManager x509mgr = new X509TrustManager()
{
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] {x509mgr}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setCookieSpec(String.valueOf(CookiePolicy.ACCEPT_ALL))
.build()).build();
}
try
{
closeableHttpClient = createHttpsClient();
closeableHttpClient.execute(post);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (KeyManagementException e)
{
e.printStackTrace();
}
上面代碼中的:
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
和
sslContext.init(null, new TrustManager[] {x509mgr}, null)
分別對應restclient設置中的1和2翼馆,這樣的話:
closeableHttpClient = createHttpsClient();
closeableHttpClient.execute(post);
調用closeableHttpClient發(fā)送post時闽瓢,就可以屏蔽post請求中的HTTPS證書校驗了埃跷。