接口中用到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;
}