1. Reasons for reporting errors

The reason why “Chain Validation failed” appears is that the certificate of the currently accessed website is invalid, as shown below:



Android will automatically verify whether the certificate of the website is valid when visiting the website to ensure the security of the application.

However, the certificate for the currently accessed site is expired, so an error is reported.


Second, solutions

There are many solutions, I baidu after the solution is:

Public static SSLSocketFactory getSSLSocketFactory() throws Exception {// Create a certificate trust manager that does not validate the certificate chain. final TrustManager[] trustAllCerts = new TrustManager[]{newX509TrustManager() {
        @Override
        public void checkClientTrusted(
                java.security.cert.X509Certificate[] chain,
                String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(
                java.security.cert.X509Certificate[] chain,
                String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            returnnew java.security.cert.X509Certificate[0]; }}}; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts,
            new java.security.SecureRandom());
    // Create an ssl socket factory with our all-trusting manager
    returnsslContext.getSocketFactory(); } // Get OkHttpClient instance object without validating any certificategetOkHttpClientInstance(){
    try{
        return new okhttp3.OkHttpClient.Builder()
                .sslSocketFactory(getSSLSocketFactory())
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
    }catch (Exception e){
        Log.e("OkHttpClientError", e.getMessage());
    }
    return null;
}Copy the code

After creating the above two methods, and then in the third party libraries Retrofit definition, custom use. The client (RequestDataByRetrofit. GetOkHttpClientInstance ()), as follows:

retrofit2.Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://gank.io/api/")
        .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
        .client(RequestDataByRetrofit.getOkHttpClientInstance())
        .build();Copy the code


At that time, Baidu saw a good solution to the problem in a simple book, and explained a variety of solutions, but now can not find where, find the follow-up to make up.