Android snippet of the day - Simple Http Post request

So, what we want is this:

  • Call a web server asynchronously
  • Display a loading dialog during the time it executes
  • Present the response html.

This code could easily be used as a base if you need to call a web service that outputs xml


The following pieces of code are all placed in an activity. Personally I've implemented these methods in a base class to have it available in every activity inheriting from my base class


The first thing to do is to insert the correct imports to use

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

This impressing amount of imports is required just for the http and http post parts of the code.

And as if that was not enough, you also need these.


These are used for dealing with the response sent from the web server

Yes, there's more!


Used for creating the progress dialog.

Creating the loading dialog

We should start by implementing the Loading dialog, this is done by overriding the method onCreateDialog of your Activity.

	public Dialog onCreateDialog(int dialogId)
           if (dialogId == DIALOG_LOADING)
                   Dialog dialog = new ProgressDialog(this);
	           ((ProgressDialog)dialog).setMessage("Please wait...");
	           return dialog;
          return null;

Before you try to compile this code, be aware that you need to declare the DIALOG_LOADING constant, which is simply an int identifying what dialog to show.

private static final int DIALOG_LOADING = 2;

This line goes somewhere inside your Activity class

What you've done so far is that you can call showDialog(DIALOG_LOADING); at any time you wish to display a indeterminate progress dialog.

If you wish to close it, simply call dismissDialog(DIALOG_LOADING);

Setting up The AsyncTask

Create an inner class within your activity that inherits from AsyncTask. This class will be responsible for sending the request and dealing with the response from the web server

	protected class MyHttpPostRequest extends AsyncTask> {
		protected ArrayList doInBackground(String...url) {
	        ArrayList result = new ArrayList();
		    // We'll need a header
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("");

		    try {
		    	// To add http post parameters to the request, we use NameValuePair
		        List nameValuePairs = new ArrayList(2);
		        nameValuePairs.add(new BasicNameValuePair("action", "saveprofile"));
		        nameValuePairs.add(new BasicNameValuePair("username", "Admin"));
		        nameValuePairs.add(new BasicNameValuePair("password", "not4u2c"));		        
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        // Execute the request
		        HttpResponse response = httpclient.execute(httppost);
		        String httpResponseText = getResponseBodyText(response);  // This is where we extract the response text from the response
		    } catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
	        return result; 
		protected void onPreExecute() {
		protected void onPostExecute( ArrayList result )  {

It may seem as a lot of code, but basically what it does is,

1) Just before it executes, in onPreExecute we show the loading dialog.
2) After it is complete, in OnPostExecute, we call manageHttpResponse(String) with the response text. This method is declared as private in your Activity. We'll come to that later.
3) The doInBackground method is what contains all the magic. Note that it calls "getResponseBodyText" which we also haven't declared yet.

Extracting the string from HttpResponse

These methods can safely be added as private methods to your MyHttpPostRequest class

	private String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
		if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
		InputStream instream = entity.getContent();
		if (instream == null) { return ""; }
		if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Too large response to be buffered in memory"); }
		String charset = getContentCharSet(entity);
		if (charset == null) {
		Reader reader = new InputStreamReader(instream, charset);
		StringBuilder buffer = new StringBuilder();
		try {
		  char[] tmp = new char[1024];
		  int l;
		while ((l = != -1) {
		  buffer.append(tmp, 0, l);
		return buffer.toString();

	prvate String getContentCharSet(final HttpEntity entity) throws ParseException {
	   if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
		String charset = null;
		if (entity.getContentType() != null) {
		 HeaderElement values[] = entity.getContentType().getElements();
		 if (values.length > 0) {
		  NameValuePair param = values[0].getParameterByName("charset");
		  if (param != null) {
		    charset = param.getValue();
	  return charset;

private String getResponseBodyText(HttpResponse response) {
	String response_text = null;
	HttpEntity entity = null;
	  entity = response.getEntity();
	  response_text = getResponseBody(entity);
	catch (ParseException e) {
	catch (IOException e) 
	  if (entity != null) {
	    try {
	    catch (IOException e1) {
 return response_text;

All that is left to do is to declare your method manageHttpResponse(String responseText) within your Activity. In this example all we do is show a toast with the html content.

 	private void parseSendSmsResponse(String responseText)
          Toast htmlMessage = Toast.makeText(this, responseText, Toast.LENGTH_LONG);


And there you have it. What you need to do is to change the url that is called (In the example Be aware of though, you should not try to modify any views in the doInBackground method of the MyHttpRequest class. That part is running in a separate thread, thus you need to use something like a Handler and Runnable to be able to change anything that is visible.

 Android snippet of the day - Show Contact Picker

This quickie will get you up and running if you need to display the android built in contact picker to select a phone number with a minimum amount of code.

 Android Video

After the huge success with Droid Streamer, we were contacted by AndroidVideo.Net and we agreed to develop an app that plays video files.

 Droid Streamer Pro

Droid Streamer Pro is an application for streaming video files directly your Android powered device.

 Free Downloads

All full versions of software previously released by EnkelAdress Software are now available for free.

Page 2 / 2

 Facebook PHP SDK login problem

Have you integrated a facebook login to your site, or are you planning to? There\'s a small bug involving the sign in process that can make your life miserable unless you know how to get around it. Here\'s one possible solution.

 Thumbs Up Immerse VR Headset

This Immerse headset from ThumbsUp offers both positive and negative sides.

 Know your limits: Web Design

You might have the best app ever created, or you might have the user friendliest web page in the world. You might even have the most useful piece of shareware ever made and still not making any money.

 DroidXplorer big in China?

According to an email DroidXplorer will be preinstalled on devices, and be featured on a set of app stores. For free.

 Would this interest you?

Page 1 / 11