如何在 Apache HttpClient 4.0 中忽略 SSL 证书错误
2022-08-31 07:23:12
如何使用 Apache HttpClient 4.0 绕过无效的 SSL 证书错误?
如何使用 Apache HttpClient 4.0 绕过无效的 SSL 证书错误?
所有其他答案要么已被弃用,要么不适用于HttpClient 4.3。
以下是在构建 http 客户端时允许所有主机名的方法。
CloseableHttpClient httpClient = HttpClients
.custom()
.setHostnameVerifier(new AllowAllHostnameVerifier())
.build();
或者,如果您使用的是版本 4.4 或更高版本,则更新后的调用如下所示:
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
您需要使用自己的 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);