新的API 中谷歌已经不再支持HttpClient在这里我们简要介绍下HttpsURLConnection 的https配置
(如果是正式颁发的证书则不需要配置这些下面代码只针对非正式的证书)
private void GetHttps() {
InputStream caInput = null;
try {
String https = "https://kyfw.12306.cn/otn/leftTicket/init";
// 从输入流中获取ca证书我们将ca证书文件存放在了assert目录下
AssetManager am = getAssets();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
caInput=am.open("srca.cer");
Certificate ca = cf.generateCertificate(caInput);
// 创建包含我们的受信任CA的KeyStore
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// 创建一个TrustManager来信任我们的KeyStore中的CA
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// 创建使用我们的TrustManager的SSLContext
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// 告诉URLConnection从我们的SSLContext中使用SocketFactory
URL url = new URL(https);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content=sb.toString();
Message message = new Message();
message.what = 0;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
caInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}