Retrofit+OKHttp忽略https证书验证

记录这个的原因,是因为很多时候,因为后台配置的证书不正确导致APP访问不到服务器数据,导致影响自身的开发进度。没几行代码,逻辑也清晰,所以下面就直接贴出工具类吧:

 package huolongluo.yeshen.byw.injection.model;

 import java.security.SecureRandom;
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; /**
* Created by 火龙裸先生 on 2018/1/26.
* <p>
* 忽略https证书验证
*/ public class SSLSocketClient
{
//获取这个SSLSocketFactory
public static SSLSocketFactory getSSLSocketFactory()
{
try
{
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} //获取TrustManager
private static TrustManager[] getTrustManager()
{
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager()
{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
{
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
{
} @Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[]{};
}
}};
return trustAllCerts;
} //获取HostnameVerifier
public static HostnameVerifier getHostnameVerifier()
{
HostnameVerifier hostnameVerifier = new HostnameVerifier()
{
@Override
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
};
return hostnameVerifier;
}
}

有了以上的工具类,通过OKHttpClient.Builder对象调用 “sslSocketFactory ”方法 和 “hostnameVerifier ” 方法。类似于如下:

Retrofit+OKHttp忽略https证书验证

简言之:

 builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
上一篇:移动端web开发技巧(转)


下一篇:HDU 5297 Y sequence 容斥 迭代