現(xiàn)場(chǎng)環(huán)境:
后端服務(wù)部署在docker內(nèi),遠(yuǎn)程調(diào)用https接口,線上報(bào)錯(cuò):unable to find valid certification path to requested target
解決方案:
設(shè)置SSLSocketFactory忽略證書(shū)校驗(yàn)
實(shí)現(xiàn)案例:
使用的cn.hutool.http.HttpRequest工具類請(qǐng)求的數(shù)據(jù),支持設(shè)置頭部、表單、body、超時(shí)時(shí)間等關(guān)鍵信息
//https請(qǐng)求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("請(qǐng)求參數(shù)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)//表單內(nèi)容
.timeout(30000)//超時(shí),毫秒
//關(guān)鍵代碼,跳過(guò)SSL證書(shū)驗(yàn)證
.setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
.charset("utf-8")
.execute().body();
} catch (HttpException e) {
log.error("登錄失敗:{}",e.toString());
}
log.info("登錄結(jié)果:{}", result);
工具類 SSLUtils.java文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-509596.html
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class SSLUtils {
/**
* 忽略https證書(shū)驗(yàn)證
* @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() {
//檢查客戶端證書(shū),若不信任該證書(shū)拋出異常,咱們自己就是客戶端不用檢查
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
//檢查服務(wù)器的證書(shū),若不信任該證書(shū)拋出異常,可以不檢查默認(rèn)都信任
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
//返回受信任的X509證書(shū)數(shù)組
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
return trustAllCerts;
}
}
強(qiáng)烈推薦一下 hutool工具類,超好使
https://www.bookstack.cn/read/hutool/http.md文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-509596.html
到了這里,關(guān)于HTTPS請(qǐng)求忽略SSL證書(shū)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!