Android uses https for network access

Android uses https for network access

I m going to work on the last day of today, and I m going to have a holiday right away, isn t it a little excited? This holiday, I m going to read the second line of code, uh... far away, let us back: I
wrote about the https workflow and how to use keytool to generate a key and save it to a cer file two days ago. Today, learn how to use https Make network access.

Basic settings
Here we use Android's native HttpURLConnection to make network requests, use my csdn blog address to simulate http requests, and github address to simulate https requests.
Remember to add network permissions:

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

HttpURLConnection basic settings:

   //https://github.com/shenglintang?tab=repositories
       //http://blog.csdn.net/lin_t_s
        URL url = new URL("https://github.com/shenglintang?tab=repositories");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setRequestMethod("GET"); 

Core code of network request:

    // sslContext 1. 2. 
        Log.e("geek", " https ==" + (connection instanceof HttpsURLConnection));
        if (connection instanceof HttpsURLConnection) {// https 
            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();
        if (responseCode == 200) {
            InputStream is = connection.getInputStream();
            Log.e("geek", "is==" + is);
            is.close();
        }
        connection.disconnect(); 

1. Simulate http request

Results of the:

2. Simulate https (no security certificate required) request

Results of the:

3. Simulate https (requires security certificate) request

Results of the:

From response==200, it can be seen that the above three network accesses are successful. Let's see
how to initialize an SSLContext in the HttpsUtil tool class:

  1. SSLContext with security certificate
    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("lin.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(inStream, "123456".toCharArray());
        keyStory.load(null, null);
       // 
        keyStory.setCertificateEntry("tsl", 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;

    } 

Explain the lin.cer file, this is the use of keytool to generate the key mentioned in the previous article, and save the information in the lin.cer file;
2. SSLContext without a security certificate

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];
        }
    }; 

Some visits may verify the host name, this is easy, return true directly:

    /**
     *  
     */
    public static HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            //TODO Auto-generated method stub
            return true;
        }
    }; 

This is the basic https usage, the demo download address:
csdn: download.csdn.net/my
github: github.com/shenglintan...