报错信息:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException
ubable to find valid certification path to requested garget
网上有好多种解决办法,都一一试了下并没有直接解决该问题;
我遇到的问题是在本地电脑环境上使用httpClient 调用https接口正常,但是在服务器中就报以上异常。
根据网上搜索到大部分解决思路是 根据 SSLContextBuilder创建httpClient 方向是正确的,但是有的是创建时获取系统默认的证书方式绕过ssl证书验证(我系统上要是访问接口的ssl证书就不报上面的异常了)。
在这说下我本地电脑环境为什么可以访问接口成功但是服务器中不可以,因为之前我在浏览器中调试过,浏览器自动把该接口的ssl证书下载到系统当中了,所以才可以。
/**
* 忽略SSL证书的HTTP Client
* @return
*/
public static CloseableHttpClient createIgnoreSSLHttpClient(){
try{
SSLContext sslContext = SSLContextBuilder
.create()
.setTrustManagers(DefaultTrustManagers.INSTANCE)
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}catch(Exception e){
//打印 创建忽略SSL证书的HTTP Client 异常日志
}
return HttpClient.createDefault();
}
/**
* http post 请求
* @param url
* @param json
* @param token
* @return
*/
public static String doPost(String url,String json,String token){
CloseableHttpClient httpClient = createIgnoreSSLHttpClient();
CloseableHttpResponse response = null;
String resultString = "";
try {
//创建Http post请求
HttpPost httpPost = new HttpPost(url);
// 如果不需传token验证则无需该行代码
httpPost.setHeader("Authorization",token);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
//执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(),"utf-8");
}catch (Exception e){
//HttpClient--post请求异常日志
}finally {
close(response,httpClient);
}
return resultString;
}
/**
* 关闭流
* @param response
* @param httpClient
*/
public static void close(CloseableHttpResponse response,CloseableHttpClient httpClient){
try {
if(response != null){
response.close();
}
if(httpClient != null){
httpClient.close();
}
}catch (Exception e){
// msg 关闭流异常日志
}
}