请求12306系统查票。之前正常的,现在提示这样的错误:
Exception in thread "main" 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
如下图:
导致原因:由于12306安全系统升级不再支持TLS 1.0,所以。以前jsoup直接可以请求的。现在会被拒绝,
解决方法有4种:
1,直接绕过HTTPS验证 TLS2.0+
/**
* 绕过HTTPS验证 TLS2.0+
*/
static public void initTLS() {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException ignored) {
}
}
调用:在请求代码前执行即可。简单方便高效
initTLS();
2:也是绕过HTTPS验证,跟第一种其实差不多。但是调用方法有区别
private static SSLSocketFactory socketFactory() {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Failed to create a SSL socket factory", e);
}
}
调用:在请求代码中执行即可
Connection.Response response = Jsoup.connect(getTicketListUrl)
.headers(header)
.timeout(6000)
.sslSocketFactory(socketFactory())
.method(Connection.Method.GET)
.execute();
注意添加这个:.sslSocketFactory(socketFactory())
3:旧版本的Jsoup有一个参数:据说加上就行了。我现在用的版本没有,估计是取消了
.validateTLSCertificates(false)
4:导入证书:请参考这个连接:
彻底解决unable to find valid certification path to requested target_Gabriel8304的博客-CSDN博客
总结:
第4种:不推荐,为什么?因为我测试了发现还是不行。不知道为什么。而且如果你写爬虫。每一个网站都要操作一次太麻烦了。
运行效果如下图:
文章来源:https://www.toymoban.com/news/detail-743455.html
成功收到返回数据并解析 文章来源地址https://www.toymoban.com/news/detail-743455.html
到了这里,关于彻底解决:SunCertPathBuilderException: unable to find valid certification path to requested target错误的方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!