Okhttp3.0 添加SSL证书

okhttp作为Android最主要的网络请求框架之一,估计从事Android开发的小伙伴没有不知道的;
okhttp一个简单请求:

Request request = new Request.Builder().get().url("https://www.baidu.com").build();

OkHttpClient.Builder builder = new OkHttpClient.Builder();

OkHttpClient client = builder.build();

 client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }

        });

上面这段代码大家都见过,没啥技术难度。
在开发中,为了网络安全会使用https,数字证书来保证网络安全,数字证书okhttp默认会提供的,但大型项目一般都会使用自己的证书,如何给okhttp添加证书呢?
直接上代码:


            CertificateFactory factory = CertificateFactory.getInstance("X.509");//设置证书类型,X.509是一种格式标准

            //证书类型
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());//KeyStore 是一个存储了证书的文件。文件包含证书的私钥,公钥和对应的数字证书的信息。
            keyStore.load(null, null);
            InputStream stream;
            Certificate certificate;//Certificate是证书信息封装的一个bean类

            if (cerPathList != null && !cerPathList.isEmpty()) {
                for (int i = 0; i < cerPathList.size(); i++) {
                    stream = context.getAssets().open(cerPathList.get(i));
                    certificate = factory.generateCertificate(stream);
                    //证书类型
                    keyStore.setCertificateEntry("alias" + i, certificate);//将每个证书封装类以键值对的方式存入KeyStore 
                }
            }

            TrustManagerFactory trustManagerFactory =       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);//通过keyStore得到信任管理器

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, "pwd".toCharArray());//通过keyStore得到密匙管理器

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();//拿到SSLSocketFactory

            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                return null;
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
            okHttpClient.sslSocketFactory(sslSocketFactory, trustManager)//设置ssl证书
            okHttpClient.build();

总结一下,

  1. 首先准备好 我们的证书,放在Assets目录下;
  2. 读取证书信息用封装成Certificate类,存入keyStore中;
  3. 获取信任管理器TrustManagerFactory, 秘钥管理器KeyManagerFactory,生成SSLContext;
  4. 通过SSLContext得到SSLSocketFactory, 通过okHttpClient.builder的sslSocketFactory添加到okhttp;

你可能感兴趣的:(Okhttp3.0 添加SSL证书)