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
import lombok.experimental.UtilityClass;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.security.cert.X509Certificate;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
@UtilityClass
public class SSLClient {
public static CloseableHttpClient createSSLClient() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
// 通过所有证书
return true;
}
}).build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// 不验证hostname
return true;
}
});
// 如果异常了,创建普通的client
return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
在执行请求前,调用上面的代码
public static String getRequest(String url, String param) {
try {
HttpGet httpGet = new HttpGet(url + "?" + param);
httpClient = SSLClient.createSSLClient();
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 发送成功
return EntityUtils.toString(httpResponse.getEntity());
} else {
// 发送失败
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
这个工具类是之前在网上找到的,已经找不到地址了,侵权删除



