Android中进行https请求信任证书问题(效率解决,小白适用)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dabendan0714/article/details/54614781

前言

    在Android开发项目中难免要进行https请求,如果你也遇到这样的问题,那么我想这片博客能对你有些帮助。

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

    这个异常指的是找不到指定的信任证书。为了避免本地一个一个添加证书的麻烦,尤其是在测试情况下。可以通过一定方法去信任所有证书,免去麻烦。
    注:这个方法虽然省事,但是缺乏安全性,使用前自行考虑。另外,本文所有方法并非自己研究所得,我只是个搬运工,为一些新人们提供方法,也给自己留作笔记.

Volley 框架信任所有https证书

    关于Volley的使用在此不做介绍。
    信任所有证书,只有两个简单的步骤:
    1.复制粘贴一个工具类,该类源自网络,针对HttpsURLConnection证书信任问题。
    2.在进行联网请求前调用该类allowAllSSL()方法

举个栗子

//在进行联网请求前调用该类allowAllSSL()方法
FakeX509TrustManager.allowAllSSL();

queue = Volley.newRequestQueue(context);
//封装请求省略
queue.add(request);

送上代码

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;

/**
* Created by Yangmu on 16/12/16.
*/

public class FakeX509TrustManager 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 FakeX509TrustManager() };
        }

        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());
    }

}

基于Okhttpclient信任https所有证书

关于Okhttpclient的使用在此依然不做介绍。
    只有两个简单的步骤:
    1.复制粘贴工具类,针对Okhttpclient证书信任问题。(方法还是源自网络,自行整理)
    2.初始化OkHttpClient对象时进行信任证书的操作
    注意:是基于Okhttpclient,也就是说类似Square公司非常好用的Retrofit的library也能使用。

举个栗子

//初始化OkHttpClient对象时进行信任证书的操作
OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
mBuilder.sslSocketFactory(TrustAllCerts.createSSLSocketFactory());
mBuilder.hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier());
client = mBuilder.build();

送上代码

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
* Created by Yangmu on 17/1/19.
*/

public class TrustAllCerts implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

    @Override
    public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}


    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,  new TrustManager[] { new TrustAllCerts() }, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }
    public static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}
关于使用方法就是这么easy,有兴趣可以研究下https证书相关模块。
展开阅读全文

没有更多推荐了,返回首页