android如何用okhttp进行https的交互

这也是个老问题了,当时问东问西问了一堆人也没什么用,结果自己整出来了。无非就是okhttp需要一个证书过滤,添加如下代码就好了。

 public static OkHttpClient okHttpClient;

    public OkhttpUtils() {
        if (null == okHttpClient) {
            okHttpClient = new OkHttpClient();
            //HTTPS
            SSLContext sc = null;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                    }

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

                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }}, new SecureRandom());
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            okHttpClient.setSslSocketFactory(sc.getSocketFactory());
            okHttpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }

你可能感兴趣的:(android如何用okhttp进行https的交互)