【第六篇】Volley之https相关
Volley之https信任所有证书实现:
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 { } @Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException { } 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) {
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());
} }
代码中调用方法如下:
HttpsTrustManager.allowAllSSL();//主要是这行实现信任所有证书的操作
String tag_string_req = "string_req";
StringRequest strReq = new StringRequest(Request.Method.POST,
your_https_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "response :"+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "max");
params.put("password", "123456");
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
信任指定的证书文件:
HurlStack代码里面有如下方法:
/**
* @param urlRewriter Rewriter to use for request URLs
* @param sslSocketFactory SSL factory to use for HTTPS connections
* HurlStack这个类的构造大家就会发现其实volley可以支持https了,同样位于toolbox包下
*/
public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) {
mUrlRewriter = urlRewriter;
mSslSocketFactory = sslSocketFactory;
}
/**
* Opens an {@link HttpURLConnection} with parameters.
* @param url
* @return an open connection
* @throws IOException
*/
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs();
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
} return connection;
}
在https协议的情况下,保证mSslSocketFactory 不为null,因此主要的问题是传进去sslSocketFactory这个参数。
stackoverflow上面有个产生这个内容的工具类:
private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
} public void checkClientTrusted(X509Certificate[] certs, String authType) {
try {
originalTrustManager.checkClientTrusted(certs, authType);
} catch (CertificateException e) {
e.printStackTrace();
}
} public void checkServerTrusted(X509Certificate[] certs, String authType) {
try {
originalTrustManager.checkServerTrusted(certs, authType);
} catch (CertificateException e) {
e.printStackTrace();
}
}
}
};
} private SSLSocketFactory getSSLSocketFactory_Certificate(String keyStoreType, int keystoreResId)
throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException { CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(keystoreResId); Certificate ca = cf.generateCertificate(caInput);
caInput.close(); if (keyStoreType == null || keyStoreType.length() == 0) {
keyStoreType = KeyStore.getDefaultType();
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore); TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers()); SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null); return sslContext.getSocketFactory();
} private SSLSocketFactory getSSLSocketFactory_KeyStore(String keyStoreType, int keystoreResId, String keyPassword)
throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException { InputStream caInput = getResources().openRawResource(keystoreResId); // creating a KeyStore containing trusted CAs if (keyStoreType == null || keyStoreType.length() == 0) {
keyStoreType = KeyStore.getDefaultType();
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(caInput, keyPassword.toCharArray()); // creating a TrustManager that trusts the CAs in the KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore); TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers()); SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null); return sslContext.getSocketFactory();
}
调用后面两个,就能获取SSLSocketFactory 内容,使用如下:
SSLSocketFactory sslSocketFactory = getSSLSocketFactory_KeyStore("BKS", R.raw.androidbksv1, "123456789");
SSLSocketFactory sslSocketFactory = getSSLSocketFactory_Certificate("BKS", R.raw.androidbksv1_cert);
http://stackoverflow.com/questions/32154115/android-volley-self-signed-https-trust-anchor-for-certification-path-not-found
【第六篇】Volley之https相关的更多相关文章
- Python之路【第六篇】:socket
Python之路[第六篇]:socket Socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字&quo ...
- 一篇读懂HTTPS:加密原理、安全逻辑、数字证书等
1.引言 HTTPS(全称: Hypertext Transfer Protocol Secure,超文本传输安全协议),是以安全为目标的HTTP通道,简单讲是HTTP的安全版.本文,就来深入介绍下其 ...
- 跟我学SpringCloud | 第六篇:Spring Cloud Config Github配置中心
SpringCloud系列教程 | 第六篇:Spring Cloud Config Github配置中心 Springboot: 2.1.6.RELEASE SpringCloud: Greenwic ...
- 跟我学SpringCloud | 第十六篇:微服务利剑之APM平台(二)Pinpoint
目录 SpringCloud系列教程 | 第十六篇:微服务利剑之APM平台(二)Pinpoint 1. Pinpoint概述 2. Pinpoint主要特性 3. Pinpoint优势 4. Pinp ...
- Android Https相关完全解析
转载: 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/48129405: 本文出自:[张鸿洋的博客] 一.概述 其实这篇文章理论 ...
- Python之路【第十六篇】:Django【基础篇】
Python之路[第十六篇]:Django[基础篇] Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了O ...
- 第六篇 :微信公众平台开发实战Java版之如何自定义微信公众号菜单
我们来了解一下 自定义菜单创建接口: http请求方式:POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/menu/create?access_to ...
- 第六篇 SQL Server安全执行上下文和代码签名
本篇文章是SQL Server安全系列的第六篇,详细内容请参考原文. SQL Server决定主体是否有必要的执行代码权限的根本途径是其执行上下文规则.这一切都可能复杂一个主体有执行代码的权限,但是却 ...
- Android Https相关完全解析 当OkHttp遇到Https
一.概述 其实这篇文章理论上不限于okhttp去访问自签名的网站,不过接上篇博文了,就叫这个了.首先要了解的事,okhttp默认情况下是支持https协议的网站的,比如https://www.baid ...
随机推荐
- OC之类与对象
1.面向过程与面向对象. 1). 完成需求1 将大象放进冰箱. a. 把冰箱门打开. b. 把大象放进去. c. 把冰箱门关上. 这是面向过程的思路. 找1个冰箱,要求这个冰箱可以自己开门,自己把大象 ...
- CodeForces 749D Leaving Auction
二分查找,$set$. 对于某一次询问,如果把人删光了,那么输出$0$ $0$. 如果只剩下$1$个人,那么输出那个人喊的最低价格. 如果剩下的人数有大于等于两个, 这时最底下出现的情景必然是红色部分 ...
- Egret --视觉编程,显示对象,事件
1,在egret中,视觉图形都是由显示对象和显示对象容器组成的: 显示对象:准确的说,就是在舞台上显示出来的,包括能真实看见的图形,文字,图片,视频等:也包括不能看见但真实存在的显示对象容器: 一:显 ...
- linux下如何查询jdk安装路径
1:echo $JAVA_HOME 使用$JAVA_HOME的话能定位JDK的安装路径的前提是配置了环境变量$JAVA_HOME,否则如下所示,根本定位不到JDK的安装路径 [root@localho ...
- AxonVR:体验有触觉有温度的VR世界
提到VR,通常指的是 Oculus Rift 及 HTC Vive的头盔:它们以视觉及听觉使你感到身处虚拟世界.头盔成功的在视觉及听觉感官上蒙骗了你,但我们体验现实的感官不仅于此.绝大多数的VR产品忽 ...
- 我理解的session和cookie
tomcat管理session 理解tomcat是如何生成session的. 当用户请求到web资源有request.getSession()这段代码的时候,request首先会对请求的url判读是否 ...
- PyQt界面编程应用与实践
一个典型的GUI应用程序可以抽象为:主界面(菜单栏.工具栏.状态栏.内容区域),二级界面(模态.非模态),信息提示(Tooltip),程序图标等组成.本篇根据作者使用PyQt5编写的一个工具,介绍如何 ...
- iOS10 CAAnimationDelegate的适配
最近在xcode8打开之前的动画代码,看到如下警告
- 用微软makecert.exe生成一个自签名的证书
RT makecert.exe不用去找,安装VS2008后,在开始菜单相应的路径找到该命令提示符:Microsoft Visual Studio 2008/Visual Studio Tools/Vi ...
- linux ll命令参数的详解
用法:ls [选项]... [文件]... 列出 FILE 的信息(默认为当前目录). 如果不指定-cftuvSUX 或--sort 选项,则根据字母大小排序. 长选项必须使用的参数对于短选项时也是必 ...