Jsoup访问https网址异常SSLHandshakeException(已解决)

爬取网页遇到的目标站点证书不合法问题。

使用jsoup爬取解析网页时,出现了如下的异常情况。

  1. 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  
  2.         at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)  
  3.         at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1627)  
  4.         at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:204)  
  5.         at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:198)  
  6.         at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:994)  
  7.         at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:142)  
  8.         at sun.security.ssl.Handshaker.processLoop(Handshaker.java:533)  
  9.         at sun.security.ssl.Handshaker.process_record(Handshaker.java:471)  
  10.         at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:904)  
  11.         at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1132)  
  12.         at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:643)  
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
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1627)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:204)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:198)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:994)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:142)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:533)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:471)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:904)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1132)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:643)

查明是无效的SSL证书问题。由于现在很多网站由http全站升级到https,可能是原站点SSL没有部署好,导致证书无效,也有可能是其证书本身就不被认可。 对于爬取其网页就会出现证书验证出错的问题。
对于使用Jsoup自带接口来下载网页的,最新版本的1.9.2有validateTLSCertificates(boolean false)接口即可。
  1. Jsoup.connect(url).timeout(30000).userAgent(UA).validateTLSCertificates(false).get()  
Jsoup.connect(url).timeout(30000).userAgent(UA).validateTLSCertificates(false).get()
java默认的证书集合里面不存在对于多数自注册的证书,对于不使用第三方库来做http请求的话,我们可以手动
创建 TrustManager 来解决。确定要建立的链接的站点,否则不推荐这种方式
  1. public static InputStream getByDisableCertValidation(String url) {  
  2.         TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {  
  3.             public X509Certificate[] getAcceptedIssuers() {  
  4.                 return new X509Certificate[0];  
  5.             }  
  6.             public void checkClientTrusted(X509Certificate[] certs, String authType) {  
  7.             }  
  8.             public void checkServerTrusted(X509Certificate[] certs, String authType) {  
  9.             }  
  10.         } };  
  11.   
  12.         HostnameVerifier hv = new HostnameVerifier() {  
  13.             public boolean verify(String hostname, SSLSession session) {  
  14.                 return true;  
  15.             }  
  16.         };  
  17.   
  18.         try {  
  19.             SSLContext sc = SSLContext.getInstance("SSL");  
  20.             sc.init(null, trustAllCerts, new SecureRandom());  
  21.             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
  22.             HttpsURLConnection.setDefaultHostnameVerifier(hv);  
  23.   
  24.             URL uRL = new URL(url);  
  25.             HttpsURLConnection urlConnection = (HttpsURLConnection) uRL.openConnection();  
  26.             InputStream is = urlConnection.getInputStream();  
  27.             return is;  
  28.         } catch (Exception e) {  
  29.         }  
  30.         return null;  
  31.     }  
public static InputStream getByDisableCertValidation(String url) {
		TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[0];
			}
			public void checkClientTrusted(X509Certificate[] certs, String authType) {
			}
			public void checkServerTrusted(X509Certificate[] certs, String authType) {
			}
		} };
	HostnameVerifier hv = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	try {
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		HttpsURLConnection.setDefaultHostnameVerifier(hv);

		URL uRL = new URL(url);
		HttpsURLConnection urlConnection = (HttpsURLConnection) uRL.openConnection();
		InputStream is = urlConnection.getInputStream();
		return is;
	} catch (Exception e) {
	}
	return null;
}</pre><br>

refer:

http://snowolf.iteye.com/blog/391931

http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient

Jsoup访问https网址异常SSLHandshakeException:
解决方式:

Jsoup.connect(url)
.timeout(30000)
.userAgent(UA)
.validateTLSCertificates(false)
.get()

欢迎大家关注【趣学程序】公众号
趣学程序

原文地址:http://blog.csdn.net/louxuez/article/details/52814538
感谢原作者的分享,谢谢。如有侵犯,请联系笔者删除。QQ:337081267

Jsoup+httpclient 模拟登陆和抓取页面 package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String css = "http://user.goodjobs.cn/personal.css"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); ////////////////////////////body////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////link////////////////////////// Elements links = doc.select("link");//对link标签有href的路径都作处理 for (Element link : links) { String hrefAttr = link.attr("href"); if (hrefAttr.contains("/personal.css")) { hrefAttr = hrefAttr.replace("/personal.css",css); Element hrefVal=link.attr("href", hrefAttr);//修改href的属性值 sb.append(hrefVal.toString()).append("\n"); } } ////////////////////////////script////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////script////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); BufferedReader in = new BufferedReader(new FileReader(infile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content = sb.toString(); out.write(content); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
### 企业微信 GET 请求 SSL 握手异常解决方案 当企业在开发过程中尝试通过 Java 发起 HTTPS 的 GET 请求到企业微信接口时,可能会遇到 `javax.net.ssl.SSLHandshakeException` 异常,并伴随错误提示 `PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target`[^1]。 此问题的根本原因是客户端无法验证服务器端返回的证书链的有效性。具体来说,Java 默认的信任库中可能缺少目标服务器所使用的 CA 根证书,或者该根证书未被 JVM 认可为可信实体[^3]。 #### 解决方案一:导入目标服务器的 CA 根证书至 JDK 信任库 可以通过手动方式将目标服务器的 CA 根证书导入到本地 JDK 的默认信任库 (`cacerts`) 中: 1. 使用浏览器访问企业微信的目标 URL 地址 (https://qyapi.weixin.qq.com),并导出其提供的 SSL 证书。 2. 将下载的 `.crt` 文件保存到本地磁盘。 3. 执行以下命令将证书安装到 JDK 的 cacerts 文件中: ```bash keytool -import -trustcacerts -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -alias weixin_cert -file /path/to/downloaded_certificate.crt ``` 这里 `$JAVA_HOME` 是指当前运行环境中的 JDK 安装路径;`changeit` 是默认密码,如果修改过则需替换实际值;`weixin_cert` 可自定义别名。 完成以上操作后重新启动应用程序即可正常发起请求而不会出上述异常[^3]。 #### 解决方案二:全局禁用 SSL 验证(不推荐用于生产环境) 对于测试阶段或非正式场合下快速解决问题可以考虑完全关闭 SSL 验证机制。注意这种方法存在安全隐患,在生产环境中应谨慎采用。 以下是实现代码片段: ```java // 添加方法忽略所有类型的HTTPS证书校验逻辑 static { try { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;} public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) {return true;} }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch(Exception e){ System.out.println(e.getMessage()); } } ``` 执行这段初始化代码之后再调用 Jsoup 或其他 HTTP 工具类就不会因为证书问题失败了[^4]。 ### 注意事项 尽管第二种方法简单易行,但由于它绕过了必要的安全性检查,因此仅适用于调试目的而不适合部署于线上服务之中。建议优先采取第一种策略来妥善处理此类情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值