I am working on a project that needs to utilize allow all certificates for a single call and whenever I tried setting the sslSocketFactory, I would receive an error indicating an ExceptionInInitializerError.
I searched SO and found this question, but it did not resolve the issue for me; same for this Git issue.
My sample code is below:
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();
Why would I be receiving an error when the params being sent are all valid and not null?
As it turns out, the issue is being caused by a NullPointerException being called deep within the okhttp3 builder method. The exact code is here:
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at okhttp3.internal.tls.BasicTrustRootIndex.<init>(BasicTrustRootIndex.java:32)
at okhttp3.internal.platform.Platform.buildTrustRootIndex(Platform.java:288)
at okhttp3.internal.platform.AndroidPlatform.buildTrustRootIndex(AndroidPlatform.java:280)
at okhttp3.internal.platform.Platform.buildCertificateChainCleaner(Platform.java:172)
at okhttp3.internal.platform.AndroidPlatform.buildCertificateChainCleaner(AndroidPlatform.java:230)
at okhttp3.internal.tls.CertificateChainCleaner.get(CertificateChainCleaner.java:41)
at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.java:694)
The cause of this issue is that I had followed a large number of examples on Stackoverflow (IE here) which tell you to build your x509 TrustManager with that return null;
line.
The fix was to simply change the one line:
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() {
//Here
return new X509Certificate[]{};
}
};
.
.
.
And that resolved the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With