http or https Get - Android Network

Android examples for Network:HTTPS SSL

Description

http or https Get

Demo Code


//package com.java2s;
import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;

import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
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;

public class Main {
    private static Map<String, String> cookieCache = new HashMap<String, String>();
    private static SSLContext sslcontext;
    private static HostnameVerifier hostnameVerifier;

    public static String httpGet(String url, Map<String, String> params)
            throws IOException {
        if (params != null && params.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=")
                        .append(urlEncode(entry.getValue())).append("&");
            }//from ww w.  j  a va 2  s.  co m
            sb.deleteCharAt(sb.lastIndexOf("&"));
            if (url.indexOf("?") > 0) {
                url += sb.toString();
            } else {
                url = url + "?" + sb.toString();
            }
        }
        return httpGet(url);
    }

    public static String httpGet(String url) throws IOException {
        URL _url = new URL(url);
        String host = _url.getHost();
        HttpURLConnection conn = getHttpURLConnection(_url);
        conn.setConnectTimeout(3000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        String cookie = cookieCache.get(host);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }
        int responseCode = conn.getResponseCode();
        StringBuffer sb = null;
        if (responseCode == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            sb = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
        }
        cookie = conn.getHeaderField("Set-Cookie");
        if (cookie != null) {
            cookieCache.put(host, cookie);
        }
        conn.disconnect();
        return sb != null ? sb.toString() : null;
    }

    private static String urlEncode(String params) {
        try {
            if (params == null) {
                return "";
            }
            return URLEncoder.encode(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return params;
        }
    }

    private static HttpURLConnection getHttpURLConnection(URL url)
            throws IOException {
        HttpURLConnection conn;
        if (url.toString().startsWith("https")) {
            HttpsURLConnection connection = (HttpsURLConnection) url
                    .openConnection();
            connection.setSSLSocketFactory(getSslcontext()
                    .getSocketFactory());
            connection.setHostnameVerifier(getHostnameVerifier());
            conn = connection;
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        return conn;
    }

    private static SSLContext getSslcontext() {
        if (sslcontext == null) {
            TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        X509Certificate[] x509Certificates, String s)
                        throws CertificateException {

                }

                @Override
                public void checkServerTrusted(
                        X509Certificate[] x509Certificates, String s)
                        throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            try {
                sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, new TrustManager[] { trustManager },
                        new java.security.SecureRandom());
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                e.printStackTrace();
            }
        }
        return sslcontext;
    }

    private static HostnameVerifier getHostnameVerifier() {
        if (hostnameVerifier == null) {
            hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };
        }
        return hostnameVerifier;
    }
}

Related Tutorials