android使用Okhttp发送https请求时信任所有证书

1、首先创建TrustAllCerts类,如下:

package com.baicells.baiboss.api.safe;
 
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
public class TrustAllCerts implements 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 new X509Certificate[0];
    }
 
    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory factory = null;
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            factory = context.getSocketFactory();
        } catch (Exception e) {
        }
        return factory;
    }
 
    public static class TrustAllHostnameVerifier implements HostnameVerifier {
 
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}

2、在okhttpclient中使用,设置sslSocketFactory和hostnameVerifier

 
OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
mBuilder.sslSocketFactory(TrustAllCerts.createSSLSocketFactory());
mBuilder.hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier());
client = mBuilder.build()

3、使用client对象发起请求,或者结合retrofit框架发起请求。

转自:https://blog.csdn.net/u011016373/article/details/82189927

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注