HTTP Request class for Android

Here is a class that can be used to make HTTP get and HTTP post requests. I haven’t commented everything but the usage should be pretty clear from the method signatures.

Note: This is for Android 1.5.


import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


import org.apache.http.client.HttpClient;

import org.apache.commons.*;
import android.util.Log;

public class HttpRequest {
	
	/**
	 * HttpGet - doesn't read cookies
	 * 
	 * @param sUrl
	 * @return
	 */
	public static HttpData get(String sUrl) {
		HttpData ret = new HttpData();
		String str;
		StringBuffer buff = new StringBuffer();
		try {
			URL url = new URL(sUrl);
			
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			while ((str = in.readLine()) != null) {
				buff.append(str);
			}
			ret.content = buff.toString();
		} catch (Exception e) {
			Log.e("HttpRequest", e.toString());
		}
		return ret;
	}
	
	

	
	/**
	 * HTTP post request
	 * 
	 * @param sUrl
	 * @param ht
	 * @return
	 * @throws Exception
	 */
	public static HttpData post(String sUrl, Hashtable<String, String> ht) throws Exception {
		StringBuffer data = new StringBuffer();
		Enumeration<String> keys = ht.keys();
		while (keys.hasMoreElements()) {
			data.append(URLEncoder.encode(keys.nextElement(), "UTF-8"));
			data.append("=");
			data.append(URLEncoder.encode(ht.get(keys.nextElement()), "UTF-8"));
			data.append("&");
		}
		return HttpRequest.post(sUrl, data.toString());		
	}
	/**
	 * HTTP post request
	 * 
	 * @param sUrl
	 * @param data
	 * @return
	 */
	public static HttpData post(String sUrl, String data) {
		StringBuffer ret = new StringBuffer();
		HttpData dat = new HttpData();
		String header;
		try {
			// Send data
			URL url = new URL(sUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
	    
			// Get the response
			
			Map<String, List<String>> headers = conn.getHeaderFields();
			Set<Entry<String, List<String>>> hKeys = headers.entrySet();
			for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
				Entry<String, List<String>> m = i.next();
				
				Log.w("HEADER_KEY", m.getKey() + "");
				dat.headers.put(m.getKey(), m.getValue().toString());
				if (m.getKey().equals("set-cookie"))
					dat.cookies.put(m.getKey(), m.getValue().toString());
			}
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				ret.append(line);
			}
			
			wr.close();
			rd.close();
		} catch (Exception e) {
			Log.e("ERROR", "ERROR IN CODE:"+e.toString());
	    }
		dat.content = ret.toString();
		return dat;		
	}
}

You will also need this class along with it.

[java]

import java.util.Hashtable;

public class HttpData {
public String content;
public Hashtable cookies = new Hashtable();
public Hashtable headers = new Hashtable();
}
[/java]

Comments

5 responses to “HTTP Request class for Android”

  1. Gez Avatar
    Gez

    Looks nice. But could you provide an example of why you might want to you use this and how? Thanks.

  2. Moazzam Avatar

    Hi Gez,

    Any Android application that needs to communicate with a website or a web application can use it. I wrote the class so I can use it to log users into their accounts and get some information from there.

    Regarding usage examples, you can use it like this:

    HttpData result;
    String url = “http://moazzam-khan.com”;
    result = HttpRequest.get();
    Log.v(“TAG”, result.content) ;

    /*
    The line above will print the HTML of the home page of this site.
    */
    String data = “user=someUser&pass=whatever”;
    result = HttpRequest.post(url, data);
    /*
    The line above is like submitting an HTML form
    result.content will contain the body of server’s response
    result.cookies will contain cookies that the server wants you to set.
    resultant.headers will contain all headers sent (including cookies)
    */

    I modified the class so it can upload files too. I will try to post it in a few days with some more comments in the code 🙂

    Hope that helps

  3. Abhi Avatar
    Abhi

    Thanks for the post.

    When do you think you will able to blog about uploading files?

    Also How would the server side code look if you were using spring mvc

    -AP

  4. Hassan Avatar
    Hassan

    Not working 🙁 Need help

  5. Moazzam Avatar

    Hi Hasan,

    Are you trying to use this class in Android 1.5? Also there is a newer version of this class on my blog. You might want to use that

Leave a Reply

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