2013-04-05

Bypass exception for developing purpose "Trust anchor for certification path not found"

Original: http://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection

Dùng bypass exception verify SSL (develop only) trong trường hợp gặp lỗi do cert ko match. Gọi trước khi execute HTTP request


/**
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts() {
       // Create a trust manager that does not validate certificate chains
       TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                     return new java.security.cert.X509Certificate[] {};
              }

              public void checkClientTrusted(X509Certificate[] chain,
                           String authType) throws CertificateException {
              }

              public void checkServerTrusted(X509Certificate[] chain,
                           String authType) throws CertificateException {
              }
       } };

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

              HttpsURLConnection
                           .setDefaultHostnameVerifier(new HostnameVerifier() {
                                  @Override
                                  public boolean verify(String hostname,
                                                SSLSession session) {
                                         return true;
                                  }
                           });
       } catch (Exception e) {
              e.printStackTrace();
       }
}

No comments:

Post a Comment