1. 程式人生 > >OKHttp請求https證書驗證

OKHttp請求https證書驗證

拿到srca.cer證書放入assets檔案中

private static SSLSocketFactory sslSocketFactory = null;
public static void getSocketFactory() {
    try {
        InputStream certificate = MyApplication.mContext.getAssets().open("srca.cer");
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"
); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try
{ if (certificate != null) certificate.close(); } catch (IOException e) { e.printStackTrace(); } SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init ( null
, trustManagerFactory.getTrustManagers(), new SecureRandom() ); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } } /** * get請求 **/ public void sendGetRepuest(String url, final CallBacks callbacks) { final Request request = new Request.Builder().url(url).build(); client.newBuilder().connectTimeout(timeOut, TimeUnit.SECONDS) .readTimeout(timeOut, TimeUnit.SECONDS) .writeTimeout(timeOut, TimeUnit.SECONDS) .sslSocketFactory(sslSocketFactory)//設定sslSocketFactory .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callbacks.onError(e.toString()); } //解析成功 @Override public void onResponse(Call call, Response response) throws IOException { if (response != null && response.isSuccessful()) { callbacks.onSuccess(response.body().string()); } else { callbacks.onError(response.toString()); } } }); } public class MyApplication extends Application { public static Context mContext = null; @Override public void onCreate() { super.onCreate(); mContext = this; OkHttpUtils.getSocketFactory(); } }