android https請求
1、將伺服器生成的.cer檔案放在 assets目錄下
2、直接看程式碼(放在工具類,在請求的地方直接呼叫即可)
public Context context;
public static void getCA(Context context){
try {
//獲取證書
InputStream stream = context.getAssets().open("_.re-buy.cn.cer");
SSLContext tls = SSLContext.getInstance("TLS");
//使用預設證書
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//去掉系統預設證書
keystore.load(null);
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(stream);
//設定自己的證書
keystore.setCertificateEntry("_.re-buy.cn", certificate);
//通過信任管理器獲取一個預設的演算法
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
//演算法工廠建立
TrustManagerFactory instance = TrustManagerFactory.getInstance(algorithm);
instance.init(keystore);
tls.init(null, instance.getTrustManagers(), null);
SSLSocketFactory socketFactory = tls.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}catch(Exception e){
e.printStackTrace();
}
}
private static HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};