0%

Android-HTTPS请求

前言

在使用Volley+OkHttp的基础上,使用https请求网络。

步骤

自定义兼容HTTPS的HurlStack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class HTTPSHurlStack extends HurlStack {
private OkHttpClient okHttpClient;
private Map<String, SSLSocketFactory> socketFactoryMap;
public HTTPSHurlStack(Map<String, SSLSocketFactory> factoryMap) {
this(new OkHttpClient(), factoryMap);
}
public HTTPSHurlStack(OkHttpClient okHttpClient, Map<String, SSLSocketFactory> factoryMap) {
this.okHttpClient = okHttpClient;
this.socketFactoryMap = factoryMap;
}
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
if ("https".equals(url.getProtocol()) && socketFactoryMap.containsKey(url.getHost())) {
HttpsURLConnection connection = (HttpsURLConnection) new OkUrlFactory(okHttpClient).open(url);
connection.setSSLSocketFactory(socketFactoryMap.get(url.getHost()));
return connection;
} else {
return new OkUrlFactory(okHttpClient).open(url);
}
}
}

导入证书

将生成的证书导入到assets或者raw目录下(没有该目录则新建)

使用SSLSocketFactory

1
2
3
4
5
6
7
8
9
10
11
private static SSLSocketFactory getSSLSocketFactory(Context context, int res, String password)
throws Exception {
InputStream inputStream = context.getResources().openRawResource(res);
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(inputStream, password.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
return sslContext.getSocketFactory();
}

源码

源码可以参考这里

延伸阅读