Trust anchor for certification path not found - Android

After upgrading Android studio, I had this problem where I only need to fetch the API from my server, I've tried to create a new .pem but I was stuck. Also have I mention that I need to use AndroidX as well so every code need to adjust, Double KO.

echo | openssl s_client -connect {{IP}}:443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

But hey I'm just starting this out and it's overwhelming. I need something to keep on going with my learning so I found this and it worked. It is said that It's not the best approach but hey need to move on and I'll be back to this when I'm comfortable with android.



import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import view.utils.AppConstants;

 * Created by Hitesh.Sahu on 11/23/2016.

public class NetworkHandler {

    public static Retrofit getRetrofit() {

        return new Retrofit.Builder()

    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        public void checkClientTrusted([] chain, String authType) throws CertificateException {

                        public void checkServerTrusted([] chain, String authType) throws CertificateException {

                        public[] getAcceptedIssuers() {
                            return new[]{};

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

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.hostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;

            OkHttpClient okHttpClient =;
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);

For Future me - try to Drop the https to http for your test server, then the logic doesn't have to change.

Reference -

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]