Android Java URLConnection

	// HTTP POST request
	private String postData(String url, Map<String, String> dataIWantToSend) throws IOException {
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String urlParameters = mapToString(dataIWantToSend);
		
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + urlParameters);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		
		//print result
		String result = response.toString();
		System.out.println(result);		
		Log.d("HTML", result);
		return result;
	}
	
	// HTTP GET request
	private String getData(String url) throws Exception {
			
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// optional default is GET
		con.setRequestMethod("GET");

		//add request header
		con.setRequestProperty("User-Agent", USER_AGENT);

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		//print result
		String result = response.toString();
		System.out.println(result);		
		Log.d("HTML", result);
		return result;

	}
	
	private String mapToString (Map<String, String> params) throws UnsupportedEncodingException {
		StringBuffer requestParams = new StringBuffer();
		 
        if (params != null && params.size() > 0) {
 
            // creates the params string, encode them using URLEncoder
            Iterator<String> paramIterator = params.keySet().iterator();
            while (paramIterator.hasNext()) {
                String key = paramIterator.next();
                String value = params.get(key);
                requestParams.append(URLEncoder.encode(key, "UTF-8"));
                requestParams.append("=").append(
                        URLEncoder.encode(value, "UTF-8"));
                requestParams.append("&");
            }

            return requestParams.toString();
        }
		return null;
	}

Class XtData

import java.io.BufferedReader;
import java.io.DataOutputStream;
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.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class XtData {

	public static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36";
	
	public static String postData(String spec, Map<String, String> postData) throws IOException {
		String result = null;
		if (spec.startsWith("https://")) {
			result = postHttps(spec, postData);
		} else if (spec.startsWith("http://")) {
			result = postHttp(spec, postData);
		}
		return result;
	}
	
	public static String getData(String spec) throws Exception  {
		String result = null;
		if (spec.startsWith("https://")) {
			result = getHttps(spec);
		} else if (spec.startsWith("http://")) {
			result = getHttp(spec);
		}
		return result;
	}
	
	private static String postHttps(String spec, Map<String, String> postData) throws IOException {
		URL obj = new URL(spec);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String urlParameters = mapToString(postData);
		
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();

		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		
		//print result
		String result = response.toString();
		return result;
	}
	
	private static String postHttp(String spec, Map<String, String> postData) throws IOException {
		URL obj = new URL(spec);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

		String urlParameters = mapToString(postData);
		
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();

		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		
		//print result
		String result = response.toString();
		return result;
	}
	
	private static String getHttps(String spec) throws Exception {
	         
	    URL obj = new URL(spec);
	    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
	 
	    // optional default is GET
	    con.setRequestMethod("GET");
	 
	    //add request header
	    con.setRequestProperty("User-Agent", USER_AGENT);
	 
	    BufferedReader in = new BufferedReader(
	            new InputStreamReader(con.getInputStream()));
	    String inputLine;
	    StringBuffer response = new StringBuffer();
	 
	    while ((inputLine = in.readLine()) != null) {
	        response.append(inputLine);
	    }
	    in.close();
	 
	    //print result
	    String result = response.toString();
	    return result;
	 
	}
	
	private static String getHttp(String spec) throws Exception {
	         
	    URL obj = new URL(spec);
	    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	 
	    // optional default is GET
	    con.setRequestMethod("GET");
	 
	    //add request header
	    con.setRequestProperty("User-Agent", USER_AGENT);
	 
	    BufferedReader in = new BufferedReader(
	            new InputStreamReader(con.getInputStream()));
	    String inputLine;
	    StringBuffer response = new StringBuffer();
	 
	    while ((inputLine = in.readLine()) != null) {
	        response.append(inputLine);
	    }
	    in.close();
	 
	    //print result
	    String result = response.toString();
	    return result;
	 
	}
	
	private static String mapToString (Map<String, String> params) throws UnsupportedEncodingException {
		StringBuffer requestParams = new StringBuffer();
		 
        if (params != null && params.size() > 0) {
 
            // creates the params string, encode them using URLEncoder
            Iterator<String> paramIterator = params.keySet().iterator();
            while (paramIterator.hasNext()) {
                String key = paramIterator.next();
                String value = params.get(key);
                requestParams.append(URLEncoder.encode(key, "UTF-8"));
                requestParams.append("=").append(
                        URLEncoder.encode(value, "UTF-8"));
                requestParams.append("&");
            }

            return requestParams.toString();
        }
		return null;
	}
}
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *