如果直接用HttpClient发送https请求的时候报错:
sun.security.validator.ValidatorException:PKIXpathbuildingfailed:sun.security.provider.certpath.SunCertPathBuilderException:unabletofindvalidcertificationpathtorequestedtarget.
一般有以下两种方式解决解决这个问题。
1.绕开校验环节,重写相关实现类
public static CloseableHttpClient getClient() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyManagementException ex) {
Logger.getLogger(VerfiyCodeUtils.class.getName()).log(Level.SEVERE, null, ex);
}
//NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpClient;
}
public static void main(String[] args){
HttpPost httpPost = new HttpPost("https:////abc");
CloseableHttpClient httpClient = getClient();
CloseableHttpResponse response = httpClient.execute(httpPost);
}
2.导出https网站的cer证书,重新生成java cacerts证书
(1)从相应https网站导出网站证书
谷歌浏览器打开https网站后,点击url地址栏前面的安全,点击证书,显示证书对话框,点击上面标签页,详细信息,下面的复制到文件,打开导出证书对话框,选择base64编码,后保存 *.cer 证书文件
一直下一步,保存证书文件,假如证书名叫test.cer。
(2)假如是windows操作系统,cmd命令行切换成jdk的安装目录下的security,如D:\jdk1.7.0_80\jre\lib\security,security目录下有一个cacerts文件,然后执行以下命令,重新生成cacerts证书。
keytool -import -v -file test.cer -storepass changeit -keystore cacerts
网友评论