Welcome to my website, have a nice day!
Dream it, Do it, Make it!

Java请求接口证书错误:unable to find valid certification path to requested target

Java请求第三方接口,接口地址是https的,但是该接口如果申请的证书是自签名证书,那么为了安全,在进行调用时Java会报错:

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

一、环境信息

  • JDK 1.8;
  • 调用方式:OKHTTP 4.9.0;

二、解决方式

设置信任所有证书。实例化一个信任所有证书的OkHttpClient实例。

    /**
     * 解决接口地址自签名证书不受信任的情况
     * <p>
     * This is very bad practice and should NOT be used in production.
     *
     * @return OkHttpClient
     */
    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

三、完整代码

详见: Okhttp GET/POST请求示例

参考:

  1. OkHttpClient Trust All SSL Certificates
  2. okHttp跳过强制https验证
  3. java客户端验证https连接(忽略证书验证和证书验证两种方式)
  4. 彻底解决unable to find valid certification path to requested target
赞(0)
未经允许禁止转载:Ddmit » Java请求接口证书错误:unable to find valid certification path to requested target

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址