Android开发手机移动程序开发Android技术知识

使用Https进行网络访问

2017-02-08  本文已影响0人  蓝枫zeke

添加网络权限

 <uses-permission android:name="android.permission.INTERNET" />

有安全证书的SSLContext

public static SSLContext getSSLContextWithCer() throws NoSuchAlgorithmException, IOException, CertificateException,
            KeyStoreException, UnrecoverableKeyException, KeyManagementException {
        // 实例化SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // 从assets中加载证书,在HTTPS通讯中最常用的是cer/crt和pem

        InputStream inStream = MyApplication.getApplication().getAssets().open("zhoujian.cer");

        /*
         * X.509 标准规定了证书可以包含什么信息,并说明了记录信息的方法 常见的X.509证书格式包括:
         * cer/crt是用于存放证书,它是2进制形式存放的,不含私钥。
         * pem跟crt/cer的区别是它以Ascii来表示,可以用于存放证书或私钥。
         */

        // 证书工厂
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inStream);

        // 密钥库
        //Pkcs12也是证书格式 PKCS#12是“个人信息交换语法”。它可以用来将x.509的证书和证书对应的私钥打包,进行交换。

        KeyStore keyStory = KeyStore.getInstance("PKCS12");

        keyStory.load(null, null);
        // 加载证书到密钥库中
        keyStory.setCertificateEntry("ass", cer);

        // 密钥管理器
        KeyManagerFactory kMFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kMFactory.init(keyStory, null);
        // 信任管理器
        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStory);

        //初始化sslContext
        sslContext.init(kMFactory.getKeyManagers(), tmFactory.getTrustManagers(), new SecureRandom());
        inStream.close();
        return sslContext;
    }
    

没有安全证书的SSLContext

public static SSLContext getSSLContextWithoutCer() throws NoSuchAlgorithmException, KeyManagementException {
        // 实例化SSLContext
        // 这里参数可以用TSL 也可以用SSL
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { trustManagers }, new SecureRandom());
        return sslContext;

    }

    private static TrustManager trustManagers = new 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];
        }
    };

网络请求的核心代码


package com.zhoujian.https;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread()
        {
            public void run()
            {
                try
                {
                    getConnection();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void getConnection() throws IOException, KeyManagementException, NoSuchAlgorithmException,
            UnrecoverableKeyException, CertificateException, KeyStoreException {

        // https://github.com/zeke123/ConstraintLayout
        // http://my.csdn.net/my/mycsdn
        URL url = new URL("https://github.com/zeke123/ConstraintLayout");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setRequestMethod("GET");

        Log.e("zhoujian", "url==" + url);
        Log.e("zhoujian", " 是否是https请求==" + (connection instanceof HttpsURLConnection));
        if (connection instanceof HttpsURLConnection) {

            //得到sslContext对象,有两种情况:1.需要安全证书,2.不需要安全证书
            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();
             //SSLContext sslContext = HttpsUtil.getSSLContextWithoutCer();
            if (sslContext != null) {
                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
               ((HttpsURLConnection) connection).setDefaultSSLSocketFactory(sslSocketFactory);
                //((HttpsURLConnection) connection).setHostnameVerifier(HttpsUtil.hostnameVerifier);
            }
        }
        int responseCode = connection.getResponseCode();
        Log.e("zhoujian", "responseCode==" + responseCode);
        if (responseCode == 200) {
            InputStream is = connection.getInputStream();
            Log.e("zhoujian", "is==" + is);
            is.close();
        }
        connection.disconnect();
    }
}

使用Https请求网络

Snip20170208_14.png

不使用Https请求网络

Snip20170208_15.png

源码下载

源码下载:https://github.com/zeke123/HttpsDemo

上一篇下一篇

猜你喜欢

热点阅读