如何忽略 Apache HttpClient 4.0 中的 SSL 证书错误

新手上路,请多包涵

如何绕过 Apache HttpClient 4.0 的无效 SSL 证书错误?

原文由 Viet 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

您需要使用自己的 TrustManager 创建 SSLContext 并使用此上下文创建 HTTPS 方案。这是代码,

 SSLContext sslContext = SSLContext.getInstance("SSL");

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkServerTrusted =============");
            }
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

原文由 ZZ Coder 发布,翻译遵循 CC BY-SA 3.0 许可协议

所有其他答案都已弃用或不适用于 HttpClient 4.3。

这是一种在构建 http 客户端时允许所有主机名的方法。

 CloseableHttpClient httpClient = HttpClients
    .custom()
    .setHostnameVerifier(new AllowAllHostnameVerifier())
    .build();

或者,如果您使用的是 4.4 或更高版本,更新后的调用如下所示:

 CloseableHttpClient httpClient = HttpClients
    .custom()
    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
    .build();

原文由 Eric 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题