接口中用到https的URL請求服務,本地測試正常。部署到linux服務器上後,請求調不通,拋出瞭如下異常,截取了片段:
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)
Caused by: 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.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
HTTPS請求涉及證書祕鑰驗證,一般請求第三方服務,很少去安裝配置對端的數字證書和校驗。只能採用繞過數字證書校驗了,對代碼進行改造,添加處理代碼如下:
public static String doPost(String url, String param){
// 構建POST請求
HttpPost httpost = new HttpPost(url);
httpost.addHeader("Content-Type", "application/json");
// 添加Header 驗證信息
httpost.addHeader("Authorization", "Bearer xyv-dcs-gua-ugu-ayde2j");
HttpEntity httpEntity = new StringEntity(param, "utf-8");
httpost.setEntity(httpEntity);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(8000).build();
httpost.setConfig(requestConfig);
String respJson = "";
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.getStackTrace();
} catch (KeyManagementException e) {
e.getStackTrace();
} catch (KeyStoreException e) {
e.getStackTrace();
}
try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build()){
logger.info("上送報文:" + param);
HttpResponse response = httpclient.execute(httpost);
respJson = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("返回報文:" + respJson);
} catch (Exception e) {
e.printStackTrace();
}
return respJson;
}