Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import android.util.Base64; import android.util.Log; public class Main { /** * Tag used on log messages. */ static final String TAG = "ODMCommonUtilities"; static String gDEBUG = ""; static String get(String endpoint) throws IOException { URL url; String html = ""; Logd(TAG, "Starting post..."); Boolean cont = true; try { url = new URL(endpoint); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + endpoint); cont = false; throw new IllegalArgumentException("Invalid url: " + endpoint); } if (cont) { html = validGet(url); } else { html = "Bad url"; } return html; } static void Logd(String inTAG, String message) { if (gDEBUG.equals("true")) Log.d(inTAG, message); } static String validGet(URL url) throws IOException { String html = ""; HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't // required to be reset like hostnames are HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); setBasicAuthentication(conn, url); int status = conn.getResponseCode(); if (status != 200) { Logd(TAG, "Failed to get from server, returned code: " + status); throw new IOException("Get failed with error code " + status); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } } catch (IOException e) { Logd(TAG, "Failed to get from server: " + e.getMessage()); } if (conn != null) { conn.disconnect(); } return html; } static void setBasicAuthentication(HttpURLConnection conn, URL url) { String userInfo = url.getUserInfo(); if (userInfo != null && userInfo.length() > 0) { String authString = Base64.encodeToString(userInfo.getBytes(), Base64.DEFAULT); conn.setRequestProperty("Authorization", "Basic " + authString); } } }