okhttpClinet set trust certificate

Keywords: Mobile iOS Session

1. There are two types of certificates

@1. The certificate purchased from the certification authority (each certificate purchased by our company requires 4000 yuan, TMD, rather than renting an additional server). If the server uses such a certificate, it can directly ignore the certificate for the mobile terminal and access it directly with https. Unlike ios, which has many trusted certificates built in, they don't need to do anything

@2. The other is a self-made certificate. It is not trusted and does not cost money to use this kind of certificate, so we need to set this kind of certificate as a trust certificate in the code.

 mHttpClient = new OkHttpClient.Builder()
                        .cache(new Cache(mContext.getExternalCacheDir(), 10 * 1024 * 1024))
                        .sslSocketFactory(sslSocketFactory, trustManager)
                        .hostnameVerifier(hostnameVerifier)//Verify that the host name matches the authentication scheme of the server
                        .addInterceptor(new LoggerInterceptor())
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .cookieJar(new CookiesManager())
                        .build();
                return mHttpClient;

2. Our request certificate is inconsistent with the server's certificate, because we also need to configure a HostnameVerifier to ignore the host verification.

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance
                        (TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(getkeyStore());
                TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
                if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                    throw new IllegalStateException("Unexpected default trust managers:" + Arrays
                            .toString(trustManagers));
                }
                X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{trustManager}, null);
                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                // notice: setting trust certificate requires a HostnameVerifier to ignore host verification 
                HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        logger.i("", hostname);
                        return true;
                    }
                };

 

Posted by joey3002 on Sat, 19 Oct 2019 08:35:18 -0700