Java后端发起https忽略SSL证书,防止报错

本文详细描述了如何在Java中使用HttpClient库进行HTTPS请求,并处理SSL证书问题,包括创建SSLContextBuilder,设置连接管理器和处理异常情况。
摘要由CSDN通过智能技术生成

#记录一下工作中遇到的小问题#

HttpPost method = new HttpPost(url);
BasicCookieStore store = new BasicCookieStore();
HttpClient httpClient = null;
String result = null;
long requestTime = 0L;

//https 请求忽略证书
try {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", sslConnectionSocketFactory).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);

    httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(cm).setDefaultCookieStore(store).build();
} catch (NoSuchAlgorithmException e) {
    logger.error("https忽略SSL证书错误  错误信息:"+e.getMessage(),e);
    throw new RuntimeException(e);
} catch (KeyStoreException e) {
    logger.error("https忽略SSL证书错误  错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    throw new RuntimeException(e);
} catch (KeyManagementException e) {
    logger.error("https忽略SSL证书错误 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    throw new RuntimeException(e);
}


if (method != null) {
    try {
       // 建立一个NameValuePair数组,用于存储欲传送的参数
       method.addHeader("Content-type",
             "application/json; charset=utf-8");
       method.setHeader("Accept", "application/json");
       method.setHeader("Connection", "close");

       long start = System.currentTimeMillis();
       HttpResponse response = httpClient.execute(method);

       requestTime = System.currentTimeMillis() - start;
       int statusCode = response.getStatusLine().getStatusCode();
       if (statusCode != HttpStatus.SC_OK) {
          logger.error("http请求失败:url=" + url + "----response=" + response.getStatusLine());

       } else {
          result = EntityUtils.toString(response.getEntity());
       }

    } catch (Exception e) {
       logger.info("URL = "+url+ " 返回结果 = ");
       logger.error("https请求错误! 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
    } finally {
       if (method != null) {
          try {
             method.releaseConnection();
             // 关闭连接
             if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();
             }
          } catch (Exception re) {
             logger.error(re.getMessage(),re);
          }
       }

    }

}
logger.info("https请求成功! 耗时={}ms Url={} return={}",requestTime, url,  result);
logger.info("URL = "+url+ " 返回结果 = "+result);

return result;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值