Okhttp访问https 12306

原创 2016年08月30日 16:49:04


下面写的类调用其getInstance方法即可获得可以访问https的HttpClient对象,使用如下:

HTTPUtils utils = new HTTPUtils(getApplicationContext);

OkHttpClient client = utils.getInstance();

在需要操作的界面获取client对象后,我们就可以访问12306了。

关于HTTPS参考如下文章:

OKHTTP通信使用(三)HTTPS

Android Https相关完全解析 当OkHttp遇到Https

package utils;

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;

/**
 * 用于访问https网络
 */
public final class HTTPSUtils {
    public OkHttpClient client = null;
    public Context mContext;
    public static HTTPSUtils httpsUtils = null;
    X509TrustManager trustManager;
    SSLSocketFactory sslSocketFactory;

    /**
     * 初始化HTTPS,添加信任证书
     *
     * @param context
     */
    public HTTPSUtils(Context context) {
        mContext = context;
        final InputStream inputStream;
        try {
            //获取放在assets下面的12306的证书
            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).build();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回获取ssl后的okhttpclient,用于请求访问https
     *
     * @param context
     * @return okhttpclient
     */
    public OkHttpClient getInstance(Context context) {
        if (client == null) {
            httpsUtils = new HTTPSUtils(context);
            if (httpsUtils.client != null) {
                return httpsUtils.client;
            }
        }
        return client;
    }
    /**
     * 以流的方式添加信任证书
     */
    /**
     * 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);
        }
    }


}

版权声明:本文为博主原创文章,转载时请著名出处:http://blog.csdn.net/dg_summer

相关文章推荐

Okhttp3 配置Https访问(使用PKCS12)证书

Okhttp3 访问Https,Https使用的证书格式为PKCS12

Android Https访问(HttpClient,Httpurlconnect,Okhttp)

Https比http有着更高的安全性.传送加密信息.有单向认证和双向认证.其中如果信任所有证书的话 那么无需将证书放入android asset文件夹下.如果不是,则需放入其文件夹中.httpclin...

Android使用OkHttp访问自签名证书的Https接口

我的简书:简书前言在Android开发中,Okhttp想必大家都不陌生,一个处理网络请求的开源项目,是安卓端最火热的轻量级框架。本人在开发过程中也用了很长一段时间了,但是基本请求的都是http接口。即...

OKHTTP的拦截器以及https访问

一、前言        上一篇博文我们介绍了okhttp的基础用法,我们还可以进一步的配置,使用起来更加方便,我主要从配置拦截器和缓存,访问https几个方面讲解,本文还是会以okhttp的wiki部...

12306Https签名证书

  • 2017-06-02 14:24
  • 155KB
  • 下载

四、基于HTTPS协议的12306抢票软件设计与实现--水平DNS并发查询分享

因为12306是全球都可以访问的网站,需要提供高并发等功能,因此在各地都提供了多个服务器,通过DNS解析,不同地区的用户访问距离本地最近的服务器来进行解析,通过这样12306来分解各地的高并发请求。但...

okHTTP与HTTPS

  • 2016-06-15 21:06
  • 7.20MB
  • 下载

okhttp实现https访问,支持Android 4.X系统https访问

这是目前最完善的Https证书校验工具类,实现了服务端和客户端之间的基于身份认证的交互,并且真正实现了 TrustManger 的 checkServerTrusted() 方法,对服务器证书域...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)