Android ignore self signed certificate

萝らか妹 提交于 2019-12-09 07:04:49

问题


My Android App is connecting to https self-signed server & it is working fine with using client certificates (.cer file).

Can Android App be connected to https self-signed server WITHOUT using client Certificates. --> If answers is YES then which library can be used for that. I know this would not be best method to achieve as it is https server, but this is what i need.


回答1:


You can use Volley Android library for that.

You will need to add the below code on the onCreate() of your application class. By overwriting the X509Certificate basically you will accept all certificates.

try {
        TrustManager[] victimizedManager = new TrustManager[]{

                new X509TrustManager() {

                    public X509Certificate[] getAcceptedIssuers() {

                        X509Certificate[] myTrustedAnchors = new X509Certificate[0];

                        return myTrustedAnchors;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, victimizedManager, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/34136694/android-ignore-self-signed-certificate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!