Android使用Https

OkHttp使用Https(OkHttp版本3.8.1)

一、使用(4步搞定)

1.初始化OkHttpClient时设置sslSocketFactory,需要两个参数。设置后即可访问https

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(getSSLSocketFactory(), getTrustManager());

2.获取信任库getTrustManager()

// 获取证书库

KeyStore keystore = getKeyStore();

// 初始化信任库工厂

TrustManagerFactory trustManagerFactory;

trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

trustManagerFactory.init(keystore);

// 获取信任库

TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {

throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));

}

X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

3.获取证书库getKeyStore()

private static KeyStore getKeyStore() throws Exception {

// 初始化证书

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

InputStream inputStream = App.instance.getAssets().open("client.cer");// 这里导入SSL证书文件

Certificate cer = certificateFactory.generateCertificate(inputStream);

inputStream.close();

// 初始化证书库,给证书库设置证书

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

keystore.load(null, null); // 双向验证时使用

keystore.setCertificateEntry("trust", cer);

return keystore;

}

}

4.getSSLSocketFactory()

private static SSLSocketFactory getSSLSocketFactory() {

try {

// 获取信任库

X509TrustManager trustManager = getTrustManager();

// 初始化SSL上下文

SSLContext sslContext = SSLContext.getInstance("TLS");

sslContext.init(null, new TrustManager[] { trustManager }, null);

SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

return sslSocketFactory;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}


二、证书文件放在assets目录下。



三、证书有自签名证书和正式证书。自签名证书是服务器的人用本地服务器的根证书自签名的,证书验证时会出现失败。正式证书需要购买

1、使用自签名证书时,要忽略证书验证,即信任所有的证书。设置hostnameVerifier,重写verify方法,返回true,即信任所有证书。默认的hHostnameVerifier对象,会验证证书

builder.hostnameVerifier(new HostnameVerifier() {

@Override

public boolean verify(String hostname, SSLSession session) {

return true;

}

});

2、正式证书的环境,根据服务器需求,可以只改url为https,不为设置sslSocketFactory,即可访问服务器


查看源码如何使用sslSocketFactory

/**源码,有demo代码*/

public Builder sslSocketFactory(

SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) {...}


在访问服务器成功后,获取response中的header,传入键值,即可获取响应头。需要全局保存这个header,再之后的每次网络请求时都要添加header

Response response = call.execute();

response.header("app_token");//app_toekn响应头的键值



Xutils3使用Https

一、使用

1.new请求参数,设置SslSocketFactory,一个参数。设置后即可访问https

RequestParams params = new RequestParams(url);

params.setSslSocketFactory(sslContext.getSocketFactory());

2.获取sslContext


HttpsUrlConnection使用Https

参考:www.jianshu.com/p/2f6ace079568

推荐阅读更多精彩内容