android 实现https通讯,通过读取cer或pfx证书

1. 通过pfx证书实现https请求

 准备好xxx.pfx证书(如放在assets目录下)
 准好证书的私钥密码

代码实现如下:

public static final String CLIENT_KET_PASSWORD="123456";
 KeyStore trustStore = KeyStore.getInstance("PKCS12", "BC");
            trustStore.load(MainActivity.this.getAssets().open("xxxx.pfx"), CLIENT_KET_PASSWORD.toCharArray());
            org.apache.http.conn.ssl.SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore, CLIENT_KET_PASSWORD.toCharArray());
            sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "utf-8");

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            HttpClient client = null;
            String msg = "";
            try
            {
                ClientConnectionManager ccm =
                        new ThreadSafeClientConnManager(params, registry);
                client = new DefaultHttpClient(ccm, params);
                HttpGet hg = new HttpGet(url);
                HttpResponse response = client.execute(hg);
                HttpEntity entity = response.getEntity();
                if (entity != null)
                {
                    InputStream instreams = entity.getContent();
                    msg = convertStreamToString(instreams);
                }
                 Log.d("result",msg);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
   **并且需要自定义SSLSocketFactory类**

public class SSLSocketFactoryEx extends SSLSocketFactory
{
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public SSLSocketFactoryEx(KeyStore truststore, char[] arry)
            throws NoSuchAlgorithmException, KeyManagementException,
            KeyStoreException, UnrecoverableKeyException
    {
        super(truststore);
        KeyManagerFactory localKeyManagerFactory =
                KeyManagerFactory.getInstance(KeyManagerFactory
                        .getDefaultAlgorithm());
        localKeyManagerFactory.init(truststore, arry);
        KeyManager[] arrayOfKeyManager =
                localKeyManagerFactory.getKeyManagers();
        TrustManager tm = new X509TrustManager()
        {

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

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

            }

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

            }
        };

        sslContext.init(arrayOfKeyManager, new TrustManager[] { tm },
                new java.security.SecureRandom());
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port,
                               boolean autoClose) throws IOException, UnknownHostException
    {
        return sslContext.getSocketFactory().createSocket(socket, host, port,
                autoClose);
    }

    @Override
    public Socket createSocket() throws IOException
    {
        return sslContext.getSocketFactory().createSocket();
    }
}

2.通过cer证书实现https请求

    /**
     * HttpsURLConnection 实现https请求
     */
    private void starHttpsCer(String urlStr) {
        HttpsURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(setCertificates(MainActivity.this.getAssets().open("xxx.cer")));
            conn.connect();
            if(conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                int ch;
                while ((ch = is.read()) != -1) {
                    bytestream.write(ch);
                }
                is.close();
                conn.disconnect();
                byte[] result = bytestream.toByteArray();
                Log.d("result",new String(result));
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

public SSLSocketFactory setCertificates(InputStream... certificates){
        try{
            //证书工厂。此处指明证书的类型
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            //创建一个证书库
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates){
                String certificateAlias = Integer.toString(index++);
                //将证书导入证书库
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try{
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e){
                    e.printStackTrace() ;
                }
            }

            //取得SSL的SSLContext实例
            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.
                    getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

//            //初始化keystore
//            KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            clientKeyStore.load(getAssets().open("client.jks"), "123456".toCharArray());
//
//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            keyManagerFactory.init(clientKeyStore, "123456".toCharArray());

//            第一个参数是授权的密钥管理器,用来授权验证。TrustManager[]第二个是被授权的证书管理器,用来验证服务器端的证书。第三个参数是一个随机数值,可以填写null
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
//            sslContext.init(null, null, new SecureRandom());
            return sslContext.getSocketFactory() ;


        } catch (Exception e){
            e.printStackTrace();
        }
        return null ;
    }

注:
如果手机上开了网络代理,有可能遇上请求失败,请关闭代理后重试

你可能感兴趣的:(android,android网络)