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")); } }
調用:
成功獲取網頁內容