您的位置:首页 > 理论基础 > 计算机网络

Okhttp3信任所有证书设置

2017-07-28 12:01 344 查看
/**
* 默认信任所有的证书
* TODO 最好加上证书认证,主流App都有自己的证书
*
* @return
*/
@SuppressLint("TrulyRandom")
private static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory sSLSocketFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllManager()},
new SecureRandom());
sSLSocketFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return sSLSocketFactory;
}

private static class TrustAllManager 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];
}
}

private static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}


OkHttp配置

//log拦截器 打印所有的log
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LogUtils.e("HttpLog",message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//初始化OkHttp
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(NetworkConfig.ConnectionTime, TimeUnit.SECONDS)
.addInterceptor(new RetryIntercepter(3))  //添加自定义拦截
.addInterceptor(loggingInterceptor)
.sslSocketFactory(createSSLSocketFactory())
.hostnameVerifier(new TrustAllHostnameVerifier())
.build();
//初始化 retrofit
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.baseUrl(baseUrl)
.build();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  okhttp3 https