2020年5月28日 星期四

Program - JAVA PKIX path building failed unable to find valid certification path to requested target

連線某網站
有些為https方式

因為需要憑證的驗證 才可以正常連線
針對不同需求的做法不同
  1. 可以從java這邊關閉憑證的驗證
  2. 或是在jdk裡註冊該網站的憑證

因需求導向 我採用1.

java console內的錯誤訊息大致如下

在連線前先掠過驗證(程式碼請服用)
Caused by: 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(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
 at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
 at sun.security.ssl.Handshaker.processLoop(Unknown Source)
 at sun.security.ssl.Handshaker.process_record(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getHeaderField(Unknown Source)
 ... 1 more
 

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
 return null;
 }

  @Override
 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 // TODO Auto-generated method stub
 }

  @Override
 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 // TODO Auto-generated method stub
 }
} };

// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
 public boolean verify(String hostname, SSLSession session) {
 return true;
 }
};

// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
 
然後就可以連線了😎
URLConnection con = url.openConnection();
 


我是參考這邊的👉點我



沒有留言:

張貼留言