HttpClient访问https,设置忽略SSL证书验证

访问https时报错:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

解决办法:

1.建立以下工具类,引用信息也标明了,需要注意,引用错了则不好用

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


/**
 * @Description 忽略证书验证
 * @Author  sky
 * @Date   2021/10/21 14:00
 */
public class CertificateValidationIgnored {

    public static HttpClient wrapClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0,
                    String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0,
                    String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    }

    public static void main(String[] args) {
    }

}

2.使用工具类,之后就是正常流程了

CertificateValidationIgnored skipHttpsUtil=new CertificateValidationIgnored();
HttpClient httpClient = (CloseableHttpClient)skipHttpsUtil.wrapClient();

你可能感兴趣的:(https,ssl,HttpClient)