关于OKHttp的Https的认证问题(全部信任)

1,新TrustAllcert类实现X509TrustManager接口:

public static class TrustAllCerts implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {}

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

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

2,方法createSSLSocketFactory()调用类TrustAllcert,获取SSLSocketFactory:

private static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory ssfFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
        ssfFactory = sc.getSocketFactory();
    } catch (Exception e) {}
    return ssfFactory;
}

3,初始化OKHttpClient配置:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(10, TimeUnit.SECONDS);
builder.sslSocketFactory(createSSLSocketFactory());
builder.hostnameVerifier((hostname, session) -> true);
OkHttpClient okHttpClient = builder.build();

你可能感兴趣的:(Android开发,android,https认证)