Android开发之信任所有https证书

我们经常会遇到在开发的开始的时候或者开发过程中,服务端开发人员都会配置https证书,这些证书一般都是自建的,那么问题就来了,服务端开发人员配置了https证书,那在Android端也是需要配置相对应的证书的,不然的话无法和服务器进行交互,获取不了相关数据,在Android端如何配置证书这里就不多阐述了,在这里我讲一讲另外一种方法,用X509TrustManager来实现信任所有https证书,这种方法不需要在Android端配置证书,好处是避免了在开发完成之后切换到正式证书需要重新配置的问题,实现的代码非常的简单,代码如下:

package com.pts80.framework.utils;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
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 Kang on 2017/1/4.
 */

public class AllowX509TrustManager implements X509TrustManager {

    private static TrustManager[] trustManagers;
    private static final X509Certificate[] _AcceptedIssuers = new
            X509Certificate[] {};

    @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 _AcceptedIssuers;
    }

    public boolean isClientTrusted(X509Certificate[] chain) {
        return true;
    }

    public boolean isServerTrusted(X509Certificate[] chain) {
        return true;
    }

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

        try {
            context = SSLContext.getInstance("SSL");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }
}
上面就是工具类了,主要实现方法是allowAllSSL()方法,在发起网络请求之前,先调用AllowX509TrustManager.allowAllSSL()方法,就能正常的和服务器进行交互了。



你可能感兴趣的:(Android开发之信任所有https证书)