备注:本处代码使用groovy和httpclient4.3作为例子进行讲述
在普通方式下,当使用httpclient进行访问某个网站时,大致使用如下的代码进行访问:
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpMethod = new HttpGet(url); response = httpclient.execute(httpMethod);
当使用上述代码来访问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
要解决此问题,可以通过如下的方式:
首先创建一个类DefaultTrustManager
class DefaultTrustManager implements X509TrustManager{ @Override void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override X509Certificate[] getAcceptedIssuers() { return null } }
然后在创建httpclient时,使用如下的代码:
def trustManagers = new TrustManager[1] trustManagers[0] = new DefaultTrustManager() SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], trustManagers, new SecureRandom()); SSLContext.setDefault(sslContext); sslContext.init(null, trustManagers, null); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build();
这样在访问某些https的网站时就能正常访问了。