服務器url 切換爲https後所有接口調用報錯javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
解決辦法:
Android項目中使用 retrofit + rxjava +mvvp 架構
故在RetrofitConfig.java 的配置文件中 初始化
initOkhttp(){}
方法中加入以下代碼
OkHttpClient.Builder builder = new OkHttpClient.Builder(); int[] certificates = {R.raw.new_dd}; String hosts[]= {"*.diandianwaimai.com"}; //builder.sslSocketFactory(SslContextFactory.getSSLSocketFactory(DDApplication.getInstance().getContext(), certificates)); //builder.hostnameVerifier(SslContextFactory.getHostnameVerifier(hosts)); try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); String certificateAlias = Integer.toString(0); keyStore.setCertificateEntry(certificateAlias, certificateFactory. generateCertificate(DDApplication.getInstance().getContext().getResources().openRawResource(R.raw.new_dd))); SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init ( null, trustManagerFactory.getTrustManagers(), new SecureRandom() ); builder.sslSocketFactory(sslContext.getSocketFactory()); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (Exception ex) { }
其中 new_dd 文件是在raw目錄下
生成.cer文件的方式給出鏈接自己去看,我就不重複了
http://blog.csdn.net/shenxiandashu/article/details/46456403