httpclient跳过SSL证书验证的写法

发布时间 2023-12-08 15:32:11作者: ashet

最近在请求https接口的时候,发生了异常:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SuncertPathBuilderException: unable to find valid certification path to requested target

无法找到到请求目标的有效证书路径(据推测应该是服务端相关证书配置出现问题)

那么如何跳过SSL证书验证来发起https请求呢

try (
        CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(
                new SSLConnectionSocketFactory(SSLContextBuilder.create().loadTrustMaterial(TrustAllStrategy.INSTANCE).build()),
                NoopHostnameVerifier.INSTANCE)
            )
            .build()
    ){
        // 然后就可以使用client绕过SSL验证请求接口了
    }