httpclient如何忽略https证书
时间: 2023-07-18 15:48:18 浏览: 199
在使用 HttpClient 进行 HTTPS 请求时,如果目标服务器的证书是自签名证书或者是使用不被信任的 CA 签发的证书时,可能会出现异常。为了解决这个问题,可以通过以下步骤忽略 HTTPS 证书验证:
1. 创建 HttpClient 对象时,使用 TrustManager 相关类忽略证书验证。示例代码如下:
```
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
```
2. 在 HttpClient 执行请求时,忽略证书验证。示例代码如下:
```
HttpGet httpGet = new HttpGet("https://example.com");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
// 处理响应
} finally {
if (response != null) {
response.close();
}
}
```
需要注意的是,忽略 HTTPS 证书验证可能会存在安全风险,建议在生产环境中谨慎使用。
阅读全文