Android SSL验证在Android5.0下无效

时间:2016-09-08 02:59:08

标签: android ssl okhttp3

我现在正在使用Okhttp作为我的网络实用程序。我发现了一个奇怪的问题,我无法在Android 5.0以下的设备上验证ssl连接(在dev下),日志打印SSL handshake aborted,这在API21上不存在。

以下是代码:

public class CertificationUtils {

public static X509TrustManager x509TrustManager;

public static SSLContext sslContext = null;

public static HostnameVerifier DO_NOT_VERIFY;

public static void init(){

    x509TrustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] x509Certificates = new X509Certificate[0];
            return x509Certificates;
        }

    };

    try {
        sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

}

}

Okhttp方面:

CertificationUtils.init();

client = new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS)
.sslSocketFactory(CertificationUtils.sslContext.getSocketFactory(), CertificationUtils.x509TrustManager)                     
.hostnameVerifier(CertificationUtils.DO_NOT_VERIFY).build();

有谁能告诉我什么是错的?

0 个答案:

没有答案