「Android誌」Android處理SSL驗證
錯誤代碼
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException:
Trust anchor for certification path not found.
----------------------------------------------------------------------------------------------------------------------
解決方式
在製做電子發票驗證時、由於遇到網站憑證的問題、處理方式為避開SSL驗證
使用時先調用 requestWithoutCA 、再使用httpsurlconnection。
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException:
Trust anchor for certification path not found.
----------------------------------------------------------------------------------------------------------------------
解決方式
在製做電子發票驗證時、由於遇到網站憑證的問題、處理方式為避開SSL驗證
使用時先調用 requestWithoutCA 、再使用httpsurlconnection。
public void requestWithoutCA() { try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { new MyTrustManager() }, new SecureRandom()); HttpsURLConnection .setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection .setDefaultHostnameVerifier(new MyHostnameVerifier()); URL url = new URL("https://certs.cac.washington.edu/CAtest/"); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); InputStream in = urlConnection.getInputStream(); // 取得输入流,并使用Reader读取 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); System.out.println("============================="); System.out.println("Contents of get request"); System.out.println("============================="); String lines; while ((lines = reader.readLine()) != null) { System.out.println(lines); } reader.close(); // 断开连接 urlConnection.disconnect(); System.out.println("============================="); System.out.println("Contents of get request ends"); System.out.println("============================="); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private class MyHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { // TODO Auto-generated method stub return true; } } private class MyTrustManager implements X509TrustManager { @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 } @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } }
留言
張貼留言