Android实现https网络通信之添加指定信任证书/信任所有证书
16lz
2021-01-26
当Android客户端访问https网站,默认情况下,受证书信任限制,无法访问,可以有两种解决方法来实现:
1、将要访问的https网站的ca证书添加到客户端信任证书列表中,此种方式为谷歌推荐,安全性高。
2、将客户端设置为信任所有证书,也就是说不验证服务器证书,此种方式实现简单,但是安全性低,不推荐使用。
直接上代码,分别实现两种方式的访问。
1、客户端添加指定信任证书
assets目录中放置ca.crt证书,此证书为https://certs.cac.washington.edu/CAtest/网站的信任证书。
public void initSSL() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = getAssets().open("ca.crt"); Certificate ca = cf.generateCertificate(in); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keystore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://certs.cac.washington.edu/CAtest/");// URL url = new URL("https://github.com"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream input = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } Log.e("TTTT", result.toString()); }
public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {// URL url = new URL("https://certs.cac.washington.edu/CAtest/"); URL url = new URL("https://github.com"); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[]{new TrustAllManager()}, null); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); connection.connect(); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; StringBuffer result = new StringBuffer(); while ((line = reader.readLine()) != null) { result.append(line); } Log.e("TTTT", result.toString()); }
更多相关文章
- 服务器端向Android客户端的推送
- 使用HBuilder打包Android和iOS,并上线
- 乐博Android客户端发布
- Android(安卓)APK签名有什么用呢?
- 搭建XMPP协议,实现自主推送消息到手机
- 写了个Android聊天客户端框架,基本聊天功能、数据库、服务器都有
- android面试题总结加强再加强版(四)
- android程序打包apk(签名的作用)
- h5(vue)嵌套ios和android双向交互