标签:
Volley支持HTTPS,但是框架中默认没有加上去,可以修改一小部分源码来实现;
一是重写Volley.java newRequestQueueInDisk方法 调用第三个构造。又因为这三个构造最后调用的都是参数最多的那个所以也可以在第三个构造中直接默认生成SSLSocketFactory实例。
二是在toolbox中添加HTTPSTrustManager类(代码网上找的),并对HurlStack的createConnetcion方法进行小小的修改
package com.android.volley.toolbox; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HTTPSTrustManager implements X509TrustManager { private static TrustManager[] trustManagers; private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { // To change body of implemented methods use File | Settings | File // Templates. } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { // To change body of implemented methods use File | Settings | File // Templates. } public boolean isClientTrusted(X509Certificate[] chain) { return true; } public boolean isServerTrusted(X509Certificate[] chain) { return true; } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { // TODO Auto-generated method stub return true; } }); SSLContext context = null; if (trustManagers == null) { trustManagers = new TrustManager[] { new HTTPSTrustManager() }; } try { context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(context .getSocketFactory()); } }
protected HttpURLConnection createConnection(URL url) throws IOException { if("https".equals(url.getProtocol().toLowerCase())){ HTTPSTrustManager.allowAllowSSL(); } return (HttpURLConnection) url.openConnection(); }
三是每次VolleyQueue之前调一次HTTPSTrustManager.allowAllowSSL();
HTTPSTrustManager.allowAllowSSL();
mVolleyQuene.add(newRequest());
默认用第二种。
标签:
原文地址:http://www.cnblogs.com/liupeipro/p/4484352.html