okhttp3.0 Ignores https certificates

Recent corporate projects require that the network protocol support https, which has not been touched much before, so this time I would like to summarize the relevant content of HTTPS in android development.


1. https Certificate

For the concepts of https and certificates, you can search for Baidu yourself.

There are two types of certificates:

1. Certificates purchased from the certification authority at the expense of money. (One of the certificates purchased by our company requires 4,000 yuan, TMD, it is better to rent an additional server.)If this type of certificate is used by the server, it can be directly ignored and accessed by https for the mobile side.Unlike ios, which has a lot of trusted certificates built in, they don't need to do anything

2. The other is a self-made certificate, which is untrusted and does not cost money to use, so we need to set this type of certificate as a trust certificate in our code.


2. How to Ignore Certificates

1. If your server buddies add a certificate, then the url of your network request will be changed from http:xx to https:xx, and if you do nothing directly by changing HTTP to https, the client will report a direct error, as shown in the following figure:

This means that if no local certificate is found, then start building an SSL to trust all certificates, ignoring the fact that certificates are.

2. Create a new class

public class SSLSocketClient {

    //Get this SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //Get TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }
}
From this class we get the SSLSocketFactory, which is used to manage certificates and trust certificates

But there is one thing to note:


Then we set up the SSLSocketFactory in okhttp, as shown in the following figure:


After running, errors will still be found, as shown in the figure:


This means that our request certificate is inconsistent with the server's certificate because we also need to configure a HostnameVerifier to ignore host authentication

3. Add another method to the class of the SLSocketClient:

//Get HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
Then configure Hostname Verifier in okhttp:


Running, can be accessed normally


IV. Overall configuration

Cop the entire tool into your project:

/**
 * Created by Anonymous on 2017/6/13.
 */

public class SSLSocketClient {

    //Get this SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //Get TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    //Get HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
}

Then configure it in okhttp
mHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(new LogInterceptor())
                    .addInterceptor(new TokenInterceptor())
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
If you are using retrofit, configure okhttp in Retrofit

retrofitAPI = new Retrofit.Builder()
                    .baseUrl(AppConfig.baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(mHttpClient)//Configure okhttp
                    .build()
                    .create(RetrofitAPI.class);

In this way, you can ignore the normal access of https certificate to your network, I android white, said incorrectly, I hope Dashen can point out, thank you!


The next article will cover how glide ignores certificate access to https pictures

Keywords: OkHttp network SSL Retrofit

Added by vB3Dev.Com on Sat, 22 Jun 2019 20:44:31 +0300