大坑,找了很多方法都是垃圾代码。
解决后帮忙点个赞给个关注哦
问题背景
调用第三方接口本机可以调通。发布到生产环境后出现这个问题。
出现的原因
使用https请求业务方接口时,需要验证SSL证书。
解决方案:
// https
CloseableHttpClient httpClient = getHttpsClient();
factory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(factory));
/**
* https设置信任所有证书
*
* @return
*/
public static CloseableHttpClient getHttpsClient() {
CloseableHttpClient httpClient;
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 | KeyManagementException | KeyStoreException e) {
log.info("httpclient 设置ssl信任证书失败", e);
}
httpClient = HttpClients.custom().setSSLContext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
return httpClient;
}