【问题标题】:How to ignore ssl certification when using org.apache.commons.httpclient?使用 org.apache.commons.httpclient 时如何忽略 ssl 认证?
【发布时间】:2018-06-08 17:13:55
【问题描述】:

当我使用 Apache 包 commons-httpclient-3.1.jar 时,我尝试使用以下逻辑来避免 ssl 认证。

TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
        };

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

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

但不幸的是,我仍然遇到错误: Https客户端证书认证错误:"javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException"

然后我选择httpclient-4.3.3.jar,上面的逻辑没用,但是如果加上下面的逻辑,就可以了。

  httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));

httpClient是DefaultHttpClient的实例,socketfactory的初始化方法:

   SSLContext ctx = SSLContext.getInstance("TLS");
   ctx.init(null, new TrustManager[] { xtm }, null);
   SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
   socketFactory.setHostnameVerifier(hostnameVerifier);             

Scheme Register 似乎是必须的。

但是对于commons-httpclient-3.1.jar包,scheme怎么注册?

提前致谢!

【问题讨论】:

    标签: ssl apache-commons-httpclient


    【解决方案1】:

    经调查,以下方式可以满足要求。

    Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("https", easyhttps);
    

    EasySSLProtocolSocketFactory 在包 commons-httpclient-contrib-3.1.jar 中

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2019-01-16
      • 2020-04-03
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多