Http
分层模型
- 应用层
- 传输层
- 网络层
- 网络接口层
Https
android端加载https链接有两种信任的方案,一种是通过信任所有的网站,此外还有一种方式就是通过校验的方式
关于OKHttp的Https的认证问题(全部信任)
- 新TrustAllcert类实现X509TrustManager接口:
public 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];}
}
- 方法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;
}
- 初始化OKHttpClient配置:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.sslSocketFactory(createSSLSocketFactory());
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
好了,搞定了。此方法是okHttp信任所有的https。
匹配证书添加安全信任规则
这里就有一个很重要的概念了,https是分为单向认证,双向认证的
-
单向认证
-
双向认证