最近,項目里請求https接口出現了以下異常問題:
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
問了度娘之后,有兩種解決方案:
1、導入證書
2、忽略證書驗證
網上方法很多,我使用了以下方法,親測有效:
CloseableHttpClient client = HttpUtil.getIgnoeSSLClient(); /** * 獲取忽略證書驗證的client * * @return * @throws Exception */ public static CloseableHttpClient getIgnoeSSLClient() throws Exception { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }).build(); //創建httpClient CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); return client; }