现场环境:
后端服务部署在docker内,远程调用https接口,线上报错:unable to find valid certification path to requested target
解决方案:
设置SSLSocketFactory忽略证书校验
实现案例:
使用的cn.hutool.http.HttpRequest工具类请求的数据,支持设置头部、表单、body、超时时间等关键信息
//https请求url
String accessTokenUrl = SSOConstants.getAuthUrl() + "/oauth/token";
Map<String, Object> params = new HashMap<>();
//加密token
String client = SSOConstants.getClientId() + ":" + SSOConstants.getClientSecret();
client = Base64.getEncoder().encodeToString(client.getBytes());
params.put("grant_type", "password");
params.put("username", userName);
params.put("password", password);
log.info("请求参数username{},password{}",userName,password);
String result = null;
try {
result = HttpRequest.post(accessTokenUrl)
.header("Authorization", "Basic " + client)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "*/*")
.header("Connection", "keep-alive")
.form(params)//表单内容
.timeout(30000)//超时,毫秒
//关键代码,跳过SSL证书验证
.setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
.charset("utf-8")
.execute().body();
} catch (HttpException e) {
log.error("登录失败:{}",e.toString());
}
log.info("登录结果:{}", result);
工具类 SSLUtils.java文章来源:https://www.toymoban.com/news/detail-509596.html
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class SSLUtils {
/**
* 忽略https证书验证
* @return
*/
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static TrustManager[] getTrustManager() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
//检查客户端证书,若不信任该证书抛出异常,咱们自己就是客户端不用检查
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
//检查服务器的证书,若不信任该证书抛出异常,可以不检查默认都信任
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
//返回受信任的X509证书数组
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
return trustAllCerts;
}
}
强烈推荐一下 hutool工具类,超好使
https://www.bookstack.cn/read/hutool/http.md文章来源地址https://www.toymoban.com/news/detail-509596.html
到了这里,关于HTTPS请求忽略SSL证书的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!