Tamic /http://www.jianshu.com/p/efcbf795e95b
尊重原创,授权请访问:http://www.banquanyin.com/u/101701130004540
之前出的一篇文章 - Retrofit 2.0 超能实践,完美支持Https传输详细介绍了使用okhttp支持https的步骤,很多人要的是所以一切Https都要免信任,实则就是全部放开,那么下面的代码就是介绍如何将okHttp进行免信任Https链接。
信任所有https
信任所有https请求,也就是放行所有的证书验证,具体可以直接将OkHttpClient
的HostnameVerifie
r设置为true
OkHttpClient client = new OkHttpClient();
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] x509Certificates,
String s) throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates,
String s) throws java.security.cert.CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
} };
try {
//构造自己的SSLContext
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
client.setSslSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
接着设置协议为 1.1(Protocol.HTTP_1_1)
client.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
目前OKhttp3.5 已经将setHostnameVerifier函数 放到builder当中了,你可以使用 OkHttpClientbuilder.HostnameVerifier进行操作,实则内部调用都一样。
衍生
目前众多框架使用okhttp, 著名的有picasso,glide, Retrofit等,通过上面的姿势,就能很好的让这些框架默认支持Https链接。
今天的文章比较简短,但实用性比价高
阅读推荐
Tamic /http://www.jianshu.com/p/efcbf795e95b
尊重原创,授权请访问:http://www.banquanyin.com/u/101701130004540
网友评论
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:744 0x7361fd74:0x00000000)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:449)
at com.squareup.okhttp.Connection.connectTls(Connection.java:235)
at com.squareup.okhttp.Connection.connectSocket(Connection.java:199)
at com.squareup.okhttp.Connection.connect(Connection.java:172)
at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:367)
at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:245)
at com.squareup.okhttp.Call.getResponse(Call.java:267)