java中调用https请求忽略ssl证书认证代码示例
更新时间:2024年10月26日 09:07:33 作者:新时代农民~
在网络请求中经常会遇到需要忽略证书认证的情况,这篇文章主要介绍了java中调用https请求忽略ssl证书认证的相关资料,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
1、获取httpclient,忽略证书认证
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有证书
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build();
// 创建主机名验证器,用于绕过主机名验证
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
// 创建 SSL 连接套接字工厂,将自定义的 SSL 上下文和主机名验证器应用于 HTTPS 连接
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
// 创建自定义的 CloseableHttpClient 实例,将 SSL 连接套接字工厂应用于 HTTP 客户端
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}2、使用put请求调用
public static String put(String url, Map<String, String> header, String param) throws Exception {
String result = "";
StringEntity entity = new StringEntity(param, "utf-8");
CloseableHttpClient httpClient = null;
try {
httpClient = createSSLClientDefault();
HttpPut httpPut = new HttpPut(url);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPut.addHeader(entry.getKey(), entry.getValue());
}
}
if (entity != null) {
entity.setContentType("application/json; charset=utf-8");
httpPut.setEntity(entity);
}
LogUtil.info("开始请求https接口:" + url );
HttpResponse httpResponse = httpClient.execute(httpPut);
LogUtil.info("put请求返回httpResponse结果:" + httpResponse);
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
LogUtil.info("put请求返回结果:" + result);
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}总结
到此这篇关于java中调用https请求忽略ssl证书认证的文章就介绍到这了,更多相关java调用https请求忽略ssl认证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot+WebMagic+MyBaties实现爬虫和数据入库的示例
WebMagic是一个开源爬虫框架,本项目通过在SpringBoot项目中使用WebMagic去抓取数据,最后使用MyBatis将数据入库。具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-10-10
关于mybatis-plus-generator的简单使用示例详解
在springboot项目中集成mybatis-plus是很方便开发的,最近看了一下plus的文档,简单用一下它的代码生成器,接下来通过实例代码讲解关于mybatis-plus-generator的简单使用,感兴趣的朋友跟随小编一起看看吧2024-03-03
idea新建Springboot项目,设置默认maven和jdk版本方式
这篇文章主要介绍了idea新建Springboot项目,设置默认maven和jdk版本方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-12-12
Java中tomcat memecached session 共享同步问题的解决办法
这篇文章主要介绍了Java中tomcat memecached session 共享同步问题的解决办法的相关资料,需要的朋友可以参考下2015-10-10
Java利用HttpClient模拟POST表单操作应用及注意事项
本文主要介绍JAVA中利用HttpClient模拟POST表单操作,希望对大家有所帮助。2016-04-04


最新评论