Okhttp3 配置Https訪問(使用PKCS12)證書
阿新 • • 發佈:2019-01-04
STEP 1 放置證書檔案
將PKCS12證書和相關的trustStore檔案放置在res/raw目錄下
STEP2 建立自定義SSLFactory
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
/**
* <b>類名稱:</b> MineSSLFactory <br/>
* <b>類描述:</b> <br/>
* <b>建立人:</b> Lincoln <br/>
* <b>修改人:</b> Lincoln <br/>
* <b>修改時間:</b> 2017年03月29日 16:11<br/>
* <b>修改備註:</b> <br/>
*
* @version 1.0.0 <br/>
*/
public class MineSSLFactory {
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.client_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();
}
}
}
}
STEP3 將自定義的SSLFactory載入到OKhttpClient中
new OkHttpClient.Builder()
.addNetworkInterceptor(interceptor)
.addNetworkInterceptor(cacheInterceptor)
.addNetworkInterceptor(new StethoInterceptor())
//將自定義SSLFactory載入到OKhttpClient,context物件就是Android 系統中常用的那個
.sslSocketFactory(HospitalSSLFactory.getSocketFactory(context))
.retryOnConnectionFailure(true)
//此處將hostnameVerifier 驗證關閉掉,會使SSL的安全性降低,如果想要使用這個驗證,請不要使用私簽證書,註釋掉下面這段程式碼,執行體驗一下
.hostnameVerifier((hostname, session) -> true)
.connectTimeout(50, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
以上程式碼配置完成後,只需要將Http協議換成Https協議即可使用.