手记

创建忽略证书验证的CloseableHttpClient

项目中需要创建忽略证书的http请求,在网上搜索了一下,好多都是大段大段的代码,并且不清不楚的。
本人阅读java源码,现提供最简洁的创建忽略证书验证的https请求。

/**
 * 获取忽略证书验证的client
 *
 * @return
* @throws Exception
 */

public CloseableHttpClient getIgnoeSSLClient() throws Exception {
   SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
      @Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
         return true;
      }
   }).build();

   //创建httpClient
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
         setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
   return client;
}
1人推荐
随时随地看视频
慕课网APP

热门评论

// 最近有了一些变化,改成这样可以用了
public CloseableHttpClient getIgnoreSSLClient() throws Exception {
   SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
      @Override
      public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
         return true;
      }
   }).build();

   //创建httpClient
   CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).
         setHostnameVerifier(new AllowAllHostnameVerifier()).build();
   return client;
}


查看全部评论