Https Connection Android

后端 未结 15 1725
萌比男神i
萌比男神i 2020-11-22 04:43

I am doing a https post and I\'m getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept

相关标签:
15条回答
  • 2020-11-22 05:45

    This is what I am doing. It simply doesn't check the certificate anymore.

    // always verify the host - dont check for certificate
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    
    /**
     * 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());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    and

        HttpURLConnection http = null;
    
        if (url.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
        } else {
            http = (HttpURLConnection) url.openConnection();
        }
    
    0 讨论(0)
  • 2020-11-22 05:47

    If you are using a StartSSL or Thawte certificate, it will fail for Froyo and older versions. You can use a newer version's CAcert repository instead of trusting every certificate.

    0 讨论(0)
  • 2020-11-22 05:48

    None of these worked for me (aggravated by the Thawte bug as well). Eventually I got it fixed with Self-signed SSL acceptance on Android and Custom SSL handling stopped working on Android 2.2 FroYo

    0 讨论(0)
提交回复
热议问题