Trusting all certificates using HttpClient over HTTPS

后端 未结 21 2337
北恋
北恋 2020-11-21 04:50

Recently posted a question regarding the HttpClient over Https (found here). I\'ve made some headway, but I\'ve run into new issues. As with my last problem, I

21条回答
  •  旧时难觅i
    2020-11-21 05:25

    There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

        public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
    
                public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
    
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = base.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", ssf, 443));
            return new DefaultHttpClient(ccm, base.getParams());
        } catch (Exception ex) {
            return null;
        }
    }
    

    and call like:

    DefaultHttpClient baseClient = new DefaultHttpClient();
    HttpClient httpClient = wrapClient(baseClient );
    

    Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

提交回复
热议问题