使用hutool的httpclient连接池 调用https服务 请忽略https服务中的证书
时间: 2023-12-14 07:26:18 浏览: 308
好的,我明白了。针对您的问题,我可以给您提供以下的代码示例:
```java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class HttpClientDemo {
public static void main(String[] args) {
SSLContext sslContext = createIgnoreVerifySSL();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create();
builder.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory);
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(builder.build());
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
HttpRequest httpRequest = HttpUtil.createGet("https://www.example.com/");
httpRequest.setConnectionRequestTimeout(5000);
httpRequest.setConnectTimeout(5000);
httpRequest.setSocketTimeout(5000);
HttpResponse httpResponse = httpRequest.execute(httpClient);
System.out.println(httpResponse.body());
}
private static SSLContext createIgnoreVerifySSL() {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
return sslContext;
}
}
```
这个示例代码中,我们使用了 hutool 的 HttpClient,同时也对 HTTPS 请求中的证书进行了忽略处理。具体来说,我们使用了 hutool 的 `cn.hutool.http.HttpRequest` 对象发起 GET 请求。在进行 HTTPS 请求的时候,我们使用了一个自定义的忽略证书的 `SSLContext` 对象。由于我们采用了忽略证书的方式,因此牵扯到网络安全问题,建议在生产环境中谨慎使用。
阅读全文