Java爬虫https网页内容报错SSLHandshakeException信任(忽略)所有SSL证书
生活随笔
收集整理的這篇文章主要介紹了
Java爬虫https网页内容报错SSLHandshakeException信任(忽略)所有SSL证书
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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出現信任彈出(訪問網頁時候彈出是否信任)
解決方案:忽略ssl證書
創建一個類忽略ssl證書
TrustSSL.java import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.*;public class TrustSSL {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}public static InputStream HttpsSSL(URL strUrl){try {SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());HttpsURLConnection conn = (HttpsURLConnection) strUrl.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());//設置超時間為5秒conn.setConnectTimeout(5 * 1000);//防止屏蔽程序抓取而返回403錯誤conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");conn.connect();//獲取服務器響應代碼int responsecode = conn.getResponseCode();if (responsecode == 200) {//得到輸入流return conn.getInputStream();} else {System.out.println("獲取不到 " + strUrl + " 源碼,服務器響應代碼為:" + responsecode);return null;}} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}return null;}public static void main(String[] args) throws Exception {HttpsSSL(new URL("url"));} }調用:
?
成功獲取網頁內容
?
轉載于:https://www.cnblogs.com/weibanggang/p/11331524.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Java爬虫https网页内容报错SSLHandshakeException信任(忽略)所有SSL证书的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [***]HZOJ 柱状图
- 下一篇: IE7不能显示PNG