Android使用OkHttp请求自签名的https网站的示例
程序员文章站
2023-12-14 13:10:58
前言
很多公司考虑到安全问题,项目中都采用https加密协议进行数据传输。但是一些公司又不想花一笔钱去ca申请证书,所以就采用自签名的证书。
okhttp默认是可以访问...
前言
很多公司考虑到安全问题,项目中都采用https加密协议进行数据传输。但是一些公司又不想花一笔钱去ca申请证书,所以就采用自签名的证书。
okhttp默认是可以访问通过ca认证的https链接,例如百度首页也是https链接()。但是如果是你们公司自签名(即自己用keytool生成的证书,而不是采用通过ca认证的证书)的服务器,okhttp是无法访问的,例如访问12306网站(),会报如下错误:
https的工作原理
https在传输数据之前需要客户端(浏览器)与服务端(网站)之间进行一次握手,在握手过程中将确立双方加密传输数据的密码信息。握手过程的简单描述如下:
- 浏览器将自己支持的一套加密算法、hash算法发送给网站。
- 网站从中选出一组加密算法与hash算法,并将自己的身份信息以证书的形式发回给浏览器。证书里面包含了网站地址,加密公钥,以及证书的颁发机构等信息。
- 浏览器获得网站证书之后,开始验证证书的合法性,如果证书信任,则生成一串随机数字作为通讯过程中对称加密的秘钥。然后取出证书中的公钥,将这串数字以及hash的结果进行加密,然后发给网站。
- 网站接收浏览器发来的数据之后,通过私钥进行解密,然后hash校验,如果一致,则使用浏览器发来的数字串使加密一段握手消息发给浏览器。
- 浏览器解密,并hash校验,没有问题,则握手结束。接下来的传输过程将由之前浏览器生成的随机密码并利用对称加密算法进行加密。
握手过程中如果有任何错误,都会使加密连接断开,从而阻止了隐私信息的传输。
使用okhttp请求自签名的https服务器数据
以下我们使用12306网站为例
1. 首先去12306网站首页下载证书
2. 将下载的证书srca.cer放到工程的assets文件夹下。
3. 添加https工具类
package com.alpha58.okhttp; import android.content.context; import java.io.ioexception; import java.io.inputstream; import java.security.generalsecurityexception; import java.security.keystore; import java.security.cert.certificate; import java.security.cert.certificatefactory; import java.util.arrays; import java.util.collection; import javax.net.ssl.keymanagerfactory; import javax.net.ssl.sslcontext; import javax.net.ssl.sslsocketfactory; import javax.net.ssl.trustmanager; import javax.net.ssl.trustmanagerfactory; import javax.net.ssl.x509trustmanager; import okhttp3.okhttpclient; /** * created by admin on 2017/03/12. */ public final class httpsutils { private okhttpclient client; public context mcontext; /** * 获取okhttpclient实例 * @return */ public okhttpclient getinstance() { return client; } /** * 初始化https,添加信任证书 * @param context */ public httpsutils(context context) { mcontext = context; x509trustmanager trustmanager; sslsocketfactory sslsocketfactory; final inputstream inputstream; try { inputstream = mcontext.getassets().open("srca.cer"); // 得到证书的输入流 try { trustmanager = trustmanagerforcertificates(inputstream);//以流的方式读入证书 sslcontext sslcontext = sslcontext.getinstance("tls"); sslcontext.init(null, new trustmanager[]{trustmanager}, null); sslsocketfactory = sslcontext.getsocketfactory(); } catch (generalsecurityexception e) { throw new runtimeexception(e); } client = new okhttpclient.builder() .sslsocketfactory(sslsocketfactory, trustmanager) .build(); } catch (ioexception e) { e.printstacktrace(); } } /** * 以流的方式添加信任证书 */ /** * returns a trust manager that trusts {@code certificates} and none other. https services whose * certificates have not been signed by these certificates will fail with a {@code * sslhandshakeexception}. * <p> * <p>this can be used to replace the host platform's built-in trusted certificates with a custom * set. this is useful in development where certificate authority-trusted certificates aren't * available. or in production, to avoid reliance on third-party certificate authorities. * <p> * <p> * <h3>warning: customizing trusted certificates is dangerous!</h3> * <p> * <p>relying on your own trusted certificates limits your server team's ability to update their * tls certificates. by installing a specific set of trusted certificates, you take on additional * operational complexity and limit your ability to migrate between certificate authorities. do * not use custom trusted certificates in production without the blessing of your server's tls * administrator. */ private x509trustmanager trustmanagerforcertificates(inputstream in) throws generalsecurityexception { certificatefactory certificatefactory = certificatefactory.getinstance("x.509"); collection<? extends certificate> certificates = certificatefactory.generatecertificates(in); if (certificates.isempty()) { throw new illegalargumentexception("expected non-empty set of trusted certificates"); } // put the certificates a key store. char[] password = "password".tochararray(); // any password will work. keystore keystore = newemptykeystore(password); int index = 0; for (certificate certificate : certificates) { string certificatealias = integer.tostring(index++); keystore.setcertificateentry(certificatealias, certificate); } // use it to build an x509 trust manager. keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance( keymanagerfactory.getdefaultalgorithm()); keymanagerfactory.init(keystore, password); trustmanagerfactory trustmanagerfactory = trustmanagerfactory.getinstance( trustmanagerfactory.getdefaultalgorithm()); trustmanagerfactory.init(keystore); trustmanager[] trustmanagers = trustmanagerfactory.gettrustmanagers(); if (trustmanagers.length != 1 || !(trustmanagers[0] instanceof x509trustmanager)) { throw new illegalstateexception("unexpected default trust managers:" + arrays.tostring(trustmanagers)); } return (x509trustmanager) trustmanagers[0]; } /** * 添加password * @param password * @return * @throws generalsecurityexception */ private keystore newemptykeystore(char[] password) throws generalsecurityexception { try { keystore keystore = keystore.getinstance(keystore.getdefaulttype()); // 这里添加自定义的密码,默认 inputstream in = null; // by convention, 'null' creates an empty key store. keystore.load(in, password); return keystore; } catch (ioexception e) { throw new assertionerror(e); } } }
4.代码中请求
public void gethttpshtml(view view) { request request = new request.builder() .url("https://kyfw.12306.cn/otn/") .build(); httpsutils httpsutils = new httpsutils(this); httpsutils.getinstance().newcall(request).enqueue(new callback() { @override public void onfailure(call call, ioexception e) { system.out.println("--------------onfailure--------------" + e.tostring()); } @override public void onresponse(call call, response response) throws ioexception { system.out.println("--------------onresponse--------------" + response.body().string()); } }); }
5. 最后能打印出这些信息就说明请求成功啦!
注意:别忘了加权限和依赖okhttp库
demo地址:https://github.com/alpha58/okhttps
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。