如果我们的ca证书是由第三方发布的不是自己生成的则不需要下面的配置
1.首先要将我们的ca证书放在工程的assert文件夹下在这里我们就不做说明了
2.下面是配置https的代码
//设置Https 并设置超时时间
private static OkHttpClient getSSLOkHttpClient(int timeOut) throws Exception {
mOkHttpClient = new OkHttpClient();//读取时长
AssetManager am = InnoFarmApplication.getAppContext().getAssets();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream caInput = am.open("ca.crt");
Certificate ca = certificateFactory.generateCertificate(caInput);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();//获取默认的TrustManagerFactory算法名称。
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
OkHttpClient.Builder builder = mOkHttpClient.newBuilder();
builder.sslSocketFactory(sslContext.getSocketFactory())
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
if (hostname.equals(HttpHelper.HOST_NAME)) {// testacloudsys.innofarms.com
return true;
}
return false;
}
});
builder.connectTimeout(timeOut, TimeUnit.SECONDS)//连接时长
.writeTimeout(timeOut, TimeUnit.SECONDS)//写入时长
.readTimeout(timeOut, TimeUnit.SECONDS);//读取时长
return builder.build();
}