I am trying to make Android app, where I can get and parse HTML (from site which doesnt have API). I am using OkHttp. The site has untrusted (but valid) certificate. I am getting:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I've already set up the official way (https://developer.android.com/training/articles/security-ssl#java) and now I need to link it with OkHttpClient.
I tried
OkHttpClient client = new OkHttpClient;
OkHttpClient.Builder builder = client.newBuilder();
builder.sslSocketFactory(sslcontext.getSocketFactory()).build();
But it doesnt work, and also it is deprecated. Thanks
Finally, the OkHttpClient is successfully able to consume the HTTPS URL secured by a self-signed certificate. 5. Conclusion In this tutorial, we learned about configuring SSL for an OkHttpClient such that it's able to trust a self-signed certificate and consume any HTTPS URL.
This approach allows you to take advantage of the self-signed certificates generated by OpenShift Container Platform and add custom trusted certificates to individual components as needed. Note that the internal infrastructure certificates remain self-signed, which might be perceived as bad practice by some security or PKI teams.
The default configuration will start a Tomcat server listening on port 8443 and expose a secured REST API accessible at “https://localhost:8443/welcome”. Now, let's use an OkHttp client to make an HTTPS request to this server and consume the “/welcome” API.
Going straight to the point, a self-signed certificate can easily be generated by resorting to the following OpenSSL command (you need to have OpenSSL installed on your system first): This command creates a self-signed certificate, valid for 365 days, using an RSA key of 2048 bits.
See this documented example for adding a known trusted certificate
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java
public CustomTrust() {
X509TrustManager trustManager;
SSLSocketFactory sslSocketFactory;
try {
trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
client = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.build();
}
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