[ 登录 ] - [ 注册 ] | 免费代理IP 数据无忧_无忧代理IP_DATA5U最新上线 | 代码示例DEMO | IP测试视频 | 用户协议

httpclient 4.5 https请求跳过证书验证

作者:数据无忧   时间:2020-09-18 13:24:53
无忧代理IP推广返现活动
再使用代理IP抓取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

解决方案:信任所有证书,并通过SslUtil.SslHttpClientBuild()方法获取CloseableHttpClient对象:

public class SslUtil {
public static CloseableHttpClient SslHttpClientBuild() {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
return httpClient;
}
private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
SSLConnectionSocketFactory socketFactory = null;
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, null);
socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
// HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return socketFactory;
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
//don't check
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
//don't check
}
}
}


福利:现在通过开发者购买代理IP,购买后联系客服最高可获   返现20%   到你的支付宝(最低35元,最高1440元)
无忧代理IP(www.data5u.com)原创文章,转载请注明出处。

微信公众号
关注微信公众号