带有 sslSocketFactory 的 Okhttp.Builder 中的

我正在处理一个项目,该项目需要利用允许所有证书进行一次调用,每当我尝试设置 sslSocketFactory 时,我都会收到一个错误,指示 ExceptionInInitializerError。

我搜索了 SO 并发现了这个问题,但它并没有为我解决问题;这个 Git 问题也一样。

我的示例代码如下:

   X509TrustManager trustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string)

                throws CertificateException {}

        public void checkServerTrusted(X509Certificate[] xcs, String string)

                throws CertificateException {}

        public X509Certificate[] getAcceptedIssuers() {

            return null;

        }

    };

    SSLContext sslContext;

    SSLSocketFactory sslSocketFactory = null;

    try {

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(null, new TrustManager[]{trustManager}, null);

        sslSocketFactory = sslContext.getSocketFactory();

    } catch (Exception e){

        e.printStackTrace();

    }

    OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory,

            trustManager).addInterceptor(interceptor).build();

当发送的参数全部有效且不为空时,为什么我会收到错误消息?


弑天下
浏览 349回答 1
1回答

慕莱坞森

事实证明,问题是由在 okhttp3 构建器方法中调用 NullPointerException 引起的。确切的代码在这里:Caused by: java.lang.NullPointerException: Attempt to get length of null array&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.tls.BasicTrustRootIndex.<init>(BasicTrustRootIndex.java:32)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.platform.Platform.buildTrustRootIndex(Platform.java:288)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.platform.AndroidPlatform.buildTrustRootIndex(AndroidPlatform.java:280)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.platform.Platform.buildCertificateChainCleaner(Platform.java:172)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.platform.AndroidPlatform.buildCertificateChainCleaner(AndroidPlatform.java:230)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.internal.tls.CertificateChainCleaner.get(CertificateChainCleaner.java:41)&nbsp; &nbsp; &nbsp; &nbsp; at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.java:694)这个问题的原因是我在 Stackoverflow(此处为IE)上遵循了大量示例,这些示例告诉您使用该行构建 x509 TrustManager return null;。解决方法是简单地更改一行:&nbsp; &nbsp; X509TrustManager trustManager = new X509TrustManager() {&nbsp; &nbsp; &nbsp; &nbsp; public void checkClientTrusted(X509Certificate[] xcs, String string)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws CertificateException {}&nbsp; &nbsp; &nbsp; &nbsp; public void checkServerTrusted(X509Certificate[] xcs, String string)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws CertificateException {}&nbsp; &nbsp; &nbsp; &nbsp; public X509Certificate[] getAcceptedIssuers() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new X509Certificate[]{};&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; .&nbsp; &nbsp; .&nbsp; &nbsp; .这解决了这个问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java