HttpClient发送https请求忽略SSL证书
没有忽略时报错
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959)
忽略https认证,就是自己构建一个x509认证,默认通过,再传到ssl配置工厂中;
public static CloseableHttpClient trustAll(){
//配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
//创建httpClient
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
return client;
}
发送请求时调用trustAll()方法返回的client;
发送POST请求
public static String doPost(Map<String, String> params, String url) throws URISyntaxException {
// 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
.setConnectionRequestTimeout(3000)
.setSocketTimeout(3000)
.build();
post.setConfig(requestConfig);
System.out.println("url=" + url);
String result = "";
try {
// 设置json格式
String strParam = JSONObject.toJSONString(params);
StringEntity paramEntity = new StringEntity(strParam);
paramEntity.setContentEncoding("utf-8");
paramEntity.setContentType("application/json");
post.setEntity(paramEntity);
//发起请求 , 调用trustAll()方法返回的client
HttpResponse httpResponse = trustAll().execute(post);
//返回结果
int statusCode = httpResponse.getStatusLine().getStatusCode();
String postReturn = EntityUtils.toString(httpResponse.getEntity());
result = "code=" + statusCode + ",result = " + postReturn;
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
参考:
https://blog.csdn.net/weixin_44671176/article/details/110230719
https://blog.csdn.net/u011221074/article/details/104675035
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!