Issue
since sslSocketFactory(javax.net.ssl.SSLSocketFactory)' is deprecated, what should I use instead? Thanks in regards... Deprecated. SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection. Sets the socket factory used to secure HTTPS connections. If unset, the system default will be used.
try {
client = new OkHttpClient().newBuilder()
.sslSocketFactory(trustCert().getSocketFactory())
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new FormBody.Builder()
.build();
Request request = new Request.Builder()
.url("https://example.com")
.method("GET", null)
.addHeader("auth-token", token)
.addHeader("Authorization", "Bearer"+" "+token)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
odgovor = response.body().string();
System.out.println(odgovor);
} catch (IOException e) {
e.printStackTrace();
}
private SSLContext trustCert() throws CertificateException,IOException, KeyStoreException,
NoSuchAlgorithmException, KeyManagementException {
AssetManager assetManager = getAssets();
InputStream is = getApplicationContext().getResources().openRawResource(R.raw.gdig2);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca = cf.generateCertificate(is);
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}
Solution
Use, #sslSocketFactory(SSLSocketFactory, X509TrustManager)
client = new okHttpClient().newBuilder().sslSocketFactory(trustCert().getSocketFactory(), (X509TrustManager) tmf.trustManagers.get(0));
Answered By - Parth Desai