屏蔽HTTPS证书校验
2017-08-31 本文已影响117人
saylst
屏蔽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发送post时,就可以屏蔽post请求中的HTTPS证书校验了。