服务器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