android webView https 5.0以上兼容5.0以下

  private SSLContext sslContext;
        public MyWebViewClient() {
            prepareSslPinning();
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            Log.d(TAG, "shouldInterceptRequest1:" + url);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                return super.shouldInterceptRequest(view,url);
            }else{
                if (!url.startsWith("https")) {
                    return null;
                }
                if (url.endsWith("favicon.ico"))
                    return null;
                return processRequest(Uri.parse(url));
            }


        /*    return null;
//            String url2 = url.replace("http://","https://");
            if (!url.startsWith("https")) {
                return null;
            }
            if (url.endsWith("favicon.ico"))
                return null;
            return processRequest(Uri.parse(url));*/

        }

      /*  @Override
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public WebResourceResponse shouldInterceptRequest(final WebView view, WebResourceRequest interceptedRequest) {
            Log.d(TAG, "shouldInterceptRequest2:");
            return null;
//            String url2 = interceptedRequest.getUrl().toString().replace("http://","https://");
            if (!interceptedRequest.getUrl().toString().startsWith("https")) {
                return null;
            }
            if (interceptedRequest.getUrl().toString().endsWith("favicon.ico"))
                return null;
            return processRequest(interceptedRequest.getUrl());


        }*/

        @Override
        public void onReceivedSslError(WebView view,
                                       SslErrorHandler handler, SslError error) {
            android.util.Log.d(TAG, "onReceivedSslError: " + view.getUrl());
            // TODO Auto-generated method stub
            // handler.cancel();// Android默认的处理方式
            handler.proceed();// 接受所有网站的证书
            // handleMessage(Message msg);// 进行其他处理
//            checkSslError(handler,view.getUrl());

        }
        private void checkSslError(final SslErrorHandler handler,final String url) {
            try {
               OkHttpClient client = SslOkHttpClientUtils.getSslClient(mContext);
               if(client == null){
                   client = new OkHttpClient();
               }
                Request request = new Request.Builder().url(url)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                   @Override
                   public void onFailure(Call call, IOException e) {
                       Log.d(TAG, "checkSslError fail" + e.getMessage());
                       handler.cancel();
                   }

                   @Override
                   public void onResponse(Call call, Response response) throws IOException {
                       Log.d(TAG, "checkSslError success" + response.code());
                       Log.d(TAG, "checkSslError success" + response.body().string());
                       handler.proceed();

                   }
               });
            }catch (Exception e){
                e.printStackTrace();
                android.util.Log.d(TAG, "checkSslError:Exception "+e.getMessage());
            }

        }
        @TargetApi(21)
        @Override
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            android.util.Log.d(TAG, "onReceivedClientCertRequest: ");
            if ((null != SslOkHttpClientUtils.clientCertPrivateKey) && ((null != SslOkHttpClientUtils.certificatesChain) && (SslOkHttpClientUtils.certificatesChain.length != 0))) {
                request.proceed(SslOkHttpClientUtils.clientCertPrivateKey, SslOkHttpClientUtils.certificatesChain);
            } else {
                request.cancel();
            }
        }
        private WebResourceResponse processRequest(Uri uri) {
            android.util.Log.d(TAG, "processRequest url: " + uri.toString());
            if (uri.toString().contains("miyoufm/prank/dist/index.html") && SslOkHttpClientUtils.activityCenterSessionId != null) { //活动中心单独使用活动中心的seesion
                SslOkHttpClientUtils.sessionid = SslOkHttpClientUtils.activityCenterSessionId;
            }
            HttpsURLConnection urlConnection = httpsUrlRequest(uri, "GET");
            try {
              /*  android.util.Log.d(TAG, "procesessionid: "+SslOkHttpClientUtils.sessionid);
                GetRequest getRequest = OkGo.get(uri.toString());
                if(SslOkHttpClientUtils.sessionid != null) {
//                    urlConnection.setRequestProperty("Cookie", SslOkHttpClientUtils.sessionid);
                    getRequest.headers("Cookie", SslOkHttpClientUtils.sessionid);
                }
                Response response = getRequest.execute();
                if(response.code() == 405){
                    android.util.Log.d(TAG, "processRequest: "+response.code()+":"+uri.toString());
                }
                android.util.Log.d(TAG, "processRequest: "+response.code()+":"+uri.toString());
                if(response.code() == 200){
                    String cookie = response.header("Set-Cookie");
                    if(cookie != null) {
                        SslOkHttpClientUtils.cookieval = cookie;
                        SslOkHttpClientUtils.sessionid = cookie.substring(0, cookie.indexOf(";"));
                    }
                }
//                String contentType = urlConnection.getContentType();
                String contentType = response.header("content-type");
                String encoding = response.header("content-encoding");
                InputStream inputStream =  response.body().byteStream();
                if (null != contentType){
                    String mimeType = contentType;
                    if (contentType.contains(";")){
                        mimeType = contentType.split(";")[0].trim();
                    }
                    //返回新的response
                    return new WebResourceResponse(mimeType, encoding, inputStream);
                }*/

                //获取请求的内容、contentType、encoding
                android.util.Log.d(TAG, "processRequest: " + urlConnection.getResponseCode() + ":" + uri.toString());
                //若返回405 尝试post请求
                if (urlConnection.getResponseCode() == 405) {
                    urlConnection = httpsUrlRequest(uri, "POST");
                    android.util.Log.d(TAG, "processRequest: " + urlConnection.getResponseCode() + ":" + uri.toString());
                }
                if (urlConnection.getResponseCode() == 200) {
                    String cookie = urlConnection.getHeaderField("Set-Cookie");
                    if (cookie != null) {
                        SslOkHttpClientUtils.cookieval = cookie;
                        SslOkHttpClientUtils.sessionid = cookie.substring(0, cookie.indexOf(";"));
                        if (uri.toString().contains("cmic_adconfiguration/app/index")) {
                            SslOkHttpClientUtils.activityCenterSessionId = cookie.substring(0, cookie.indexOf(";"));
                        }
                    }
                }
                String contentType = urlConnection.getContentType();
                String encoding = urlConnection.getContentEncoding();
                InputStream inputStream = urlConnection.getInputStream();
                if (null != contentType) {
                    String mimeType = contentType;
                    if (contentType.contains(";")) {
                        mimeType = contentType.split(";")[0].trim();
                    }
                    //返回新的response
                    return new WebResourceResponse(mimeType, encoding, inputStream);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                android.util.Log.d(TAG, "MalformedURLException: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                android.util.Log.d(TAG, "IOException: " + e.getMessage());
            }/*finally {
                if(urlConnection!=null){
                    urlConnection.disconnect();
                }
            }*/
            return null;
        }

        private HttpsURLConnection httpsUrlRequest(Uri uri, String requstType) {
            HttpsURLConnection urlConnection = null;
            try {
                //设置连接
                URL url = new URL(uri.toString());
                urlConnection = (HttpsURLConnection) url.openConnection();
                android.util.Log.d(TAG, "procesessionid: " + SslOkHttpClientUtils.sessionid);
                if (SslOkHttpClientUtils.sessionid != null) {
                    urlConnection.setRequestProperty("Cookie", SslOkHttpClientUtils.sessionid);
                }

                //为request设置SSL Socket Factory
                urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                urlConnection.setConnectTimeout(3000);
                urlConnection.setRequestMethod(requstType);
                urlConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        android.util.Log.d(TAG, "verify: " + hostname);
                        if (hostname.equals("www.wemeetyou.cn") || hostname.equals("221.176.34.113"))
                            return true;
                        return false;
                    }
                });
                return urlConnection;

            } catch (MalformedURLException e) {
                e.printStackTrace();
                android.util.Log.d(TAG, "MalformedURLException: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                android.util.Log.d(TAG, "IOException: " + e.getMessage());
            }
            return null;
        }

        private void prepareSslPinning() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SslOkHttpClientUtils.getCertificates(mContext);
            }else{
                SslOkHttpClientUtils.cookieval = null;
                SslOkHttpClientUtils.sessionid = null;
                SslOkHttpClientUtils.activityCenterSessionId = null;
                sslContext = SslOkHttpClientUtils.getSSLContext(mContext);
            }

        }

public class SslOkHttpClientUtils {
    public static final String TAG = "SslOkHttpClientUtils";

    public static final String KEY_STORE_TYPE_P12 = "PKCS12";//证书类型

    private static OkHttpClient client;
    private static SSLContext sslContext;
    public static String sessionid;
    public static String cookieval;
    public static String activityCenterSessionId;
    public static X509Certificate[] certificatesChain;
    public static PrivateKey clientCertPrivateKey;

    public static OkHttpClient getSslClient(Context context) {
        try {
            if(client == null) {
//                InputStream trustKey = context.getAssets().open("ca.cer");
//                InputStream clientKeyP12 = context.getAssets().open("client.p12");
                InputStream trustKey = context.getAssets().open("ca_test.cer");
                InputStream clientKeyP12 = context.getAssets().open("client_test.p12");
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                sslContext = SSLContext.getInstance("TLS");
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null);
//                trustStore.load(trustKey, trustPassword.toCharArray());
                trustStore.setCertificateEntry("0", certificateFactory.generateCertificate(trustKey));
                if (trustKey != null) {
                    trustKey.close();
                }
                KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
                keyStore.load(clientKeyP12, "123456".toCharArray());
              /*  KeyStore keyStore = KeyStore.getInstance("BKS");
                keyStore.load(clientKeyP12, clientPassword.toCharArray());*/
                    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManagerFactory.init(trustStore);
                    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];
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManagerFactory.init(keyStore, "123456".toCharArray());
                    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
                    client =  new OkHttpClient().newBuilder()
                            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
                            .followRedirects(false)
                            .followSslRedirects(false)
                            .hostnameVerifier(new HostnameVerifier() {
                                @Override
                                public boolean verify(String hostname, SSLSession session) {
                                    Log.d(TAG, "verify: "+hostname);
                                    if(hostname.equals("www.wemeetyou.cn") || hostname.equals("221.176.34.113"))
                                        return true;
                                    return false;
                                }
                            })
                            .build();
                return client;
            }
            return client;
        } catch (Exception e) {
            e.printStackTrace();
            android.util.Log.d(TAG, "exception222:"+e.toString());
            return null;
        }
    }
    public static SSLContext getSSLContext(Context context){
        try {
            if(sslContext == null) {
//                InputStream trustKey = context.getAssets().open("ca.cer");
//                InputStream clientKeyP12 = context.getAssets().open("client.bks");
                InputStream trustKey = context.getAssets().open("ca_test.cer");
                InputStream clientKeyP12 = context.getAssets().open("client_test.bks");
                sslContext = SSLContext.getInstance("TLS");
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                KeyStore keyStore = KeyStore.getInstance("BKS");
                keyStore.load(clientKeyP12, "123456".toCharArray());
                clientKeyP12.close();
                trustStore.load(null);
                Log.d(TAG, "getSSLContext: 1");
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                trustStore.setCertificateEntry("0", certificateFactory.generateCertificate(trustKey));
                if (trustKey != null) {
                    trustKey.close();
                }
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
                trustManagerFactory.init(trustStore);
                keyManagerFactory.init(keyStore, "123456".toCharArray());
                sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
                Log.d(TAG, "getSSLContext: success");
            }
            return sslContext;
        } catch (Exception e) {
            e.printStackTrace();
            android.util.Log.d(TAG, "exception222:"+e.toString());
            return null;
        }

    }

    public static void getCertificates(Context context){
        if(clientCertPrivateKey == null) {
            try {

                KeyStore clientKeyStore = KeyStore.getInstance("PKCS12");
//                clientKeyStore.load(context.getAssets().open("client.p12"), "123456".toCharArray());
                clientKeyStore.load(context.getAssets().open("client_test.p12"), "123456".toCharArray());
                Enumeration<?> localEnumeration;
                localEnumeration = clientKeyStore.aliases();
                while (localEnumeration.hasMoreElements()) {
                    String str3 = (String) localEnumeration.nextElement();
                    clientCertPrivateKey = (PrivateKey) clientKeyStore.getKey(str3, "123456".toCharArray());
                    if (clientCertPrivateKey != null) {
                        Certificate[] arrayOfCertificate = clientKeyStore.getCertificateChain(str3);
                        certificatesChain = new X509Certificate[arrayOfCertificate.length];
                        for (int j = 0; j < certificatesChain.length; j++) {
                            certificatesChain[j] = ((X509Certificate) arrayOfCertificate[j]);
                        }
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            } catch (CertificateException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值