關於Okhttp3 https雙向驗證實現程式碼
使用前提:
okhttp3
官網:http://square.github.io/okhttp/
可能不同的情況會出現不同的情況,所以只能說我的程式碼邏輯不是百分之百可以適應不同環境的app,僅僅提供一個參考
1)首先準備,客戶端證書,服務端證書
本程式碼使用的證書是:client.p12,trust.bks ,並將證書存放到res/raw資料夾下
2)書寫程式碼:
public class MySSLSocketFactory { private static final String KEY_STORE_TYPE_BKS = "bks";//證書型別 private static final String KEY_STORE_TYPE_P12 = "PKCS12";//證書型別 private static final String KEY_STORE_PASSWORD = "****";//證書密碼(應該是客戶端證書密碼) private static final String KEY_STORE_TRUST_PASSWORD = "***";//授信證書密碼(應該是服務端證書密碼) public static SSLSocketFactory getSocketFactory(Context context) { InputStream trust_input = context.getResources().openRawResource(R.raw.trust);//伺服器授信證書 InputStream client_input = context.getResources().openRawResource(R.raw.client);//客戶端證書 try { SSLContext sslContext = SSLContext.getInstance("TLS"); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(trust_input, KEY_STORE_TRUST_PASSWORD.toCharArray()); KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12); keyStore.load(client_input, KEY_STORE_PASSWORD.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, KEY_STORE_PASSWORD.toCharArray()); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); SSLSocketFactory factory = sslContext.getSocketFactory(); return factory; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { trust_input.close(); client_input.close(); } catch (IOException e) { e.printStackTrace(); } } }
3)okhttps呼叫
OkHttpClient mOkHttpClient
= new OkHttpClient.Builder().sslSocketFactory(MySSLSocketFactory.getSocketFactory(context)).build();這樣就可以得到對應添加了Https協議的網路請求客戶端
4)同時,正常該程式碼也適合AsynHttpClient框架的https整合
順便打個廣告
騰訊視訊會員,搜狐會員賬號長期供貨,比官網價錢低,穩定不掉線,需要的可以加qq:1059876295