• Okhttp https


    1. 绕过CA证书,不建议使用

    private void ingoreCA() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext 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());
    okHttpClient.setSslSocketFactory(sc.getSocketFactory());
    okHttpClient.setHostnameVerifier(new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
    return true;
    }
    });
    }

    2. 设置CA

    private SSLSocketFactory getSSLSocketFactory()
    throws CertificateException, KeyStoreException, IOException,
    NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = ZhislandApplication.APP_CONTEXT.getResources().openRawResource(R.raw.api); // your certificate file
    Certificate ca = cf.generateCertificate(caInput);
    caInput.close();
    KeyStore keyStore = KeyStore.getInstance("BKS");
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, wrappedTrustManagers, null);
    return sslContext.getSocketFactory();
    }

    private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
    return new TrustManager[]{
    new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() {
    return originalTrustManager.getAcceptedIssuers();
    }

    public void checkClientTrusted(X509Certificate[] certs, String authType) {
    try {
    originalTrustManager.checkClientTrusted(certs, authType);
    } catch (CertificateException ignored) {
    }
    }

    public void checkServerTrusted(X509Certificate[] certs, String authType) {
    try {
    originalTrustManager.checkServerTrusted(certs, authType);
    } catch (CertificateException ignored) {
    }
    }
    }
    };
    }
  • 相关阅读:
    堆、栈、值类型、引用类型分析总结 Part 2
    DataGridView打印
    学习使用ArrayList
    C#与Java之比较
    【原创】串口通信测试程序
    彩色校验码的制作
    C#中使用进度条
    【原创】 Ajax之ModalPopup编程实例
    常用正则表达式
    堆、栈、值类型、引用类型分析总结 Part 1
  • 原文地址:https://www.cnblogs.com/lianghui66/p/5567432.html
Copyright © 2020-2023  润新知