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

Introduction

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

Setup

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.

import android.net.ParseException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

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

Yes, there's more!

import android.app.ProgressDialog;

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.

	@Override
	public Dialog onCreateDialog(int dialogId)
	{		 
           if (dialogId == DIALOG_LOADING)
	   {
                   Dialog dialog = new ProgressDialog(this);
	           dialog.setTitle("Preparing");
	           ((ProgressDialog)dialog).setMessage("Please wait...");
	           ((ProgressDialog)dialog).setIndeterminate(true);
	           dialog.setCancelable(false);   
	           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> {
		@Override
		protected ArrayList doInBackground(String...url) {
	        ArrayList result = new ArrayList();
		    // We'll need a header
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://www.enkeladress.com");

		    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
		        result.add(httpResponseText);		        
		    } catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
	        return result; 
		}
		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_LOADING);
		}
		@Override
		protected void onPostExecute( ArrayList result )  {
			  super.onPostExecute(result);	 
			 manageHttpResponse(result.get(0));
		         dismissDialog(DIALOG_LOADING);	      
		}
	}		

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) {
		 charset = HTTP.DEFAULT_CONTENT_CHARSET;
		}
		Reader reader = new InputStreamReader(instream, charset);
		StringBuilder buffer = new StringBuilder();
		try {
		  char[] tmp = new char[1024];
		  int l;
		while ((l = reader.read(tmp)) != -1) {
		  buffer.append(tmp, 0, l);
		 }
		}
		finally 
		{
		 reader.close();
		}
		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;
	try 
	{
	  entity = response.getEntity();
	  response_text = getResponseBody(entity);
	} 
	catch (ParseException e) {
	  e.printStackTrace();
	} 
	catch (IOException e) 
	{
	  if (entity != null) {
	    try {
	      entity.consumeContent();
	    } 
	    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);
          htmlMessage.show();
        }

Conclusion

And there you have it. What you need to do is to change the url that is called (In the example http://www.enkeladress.com). 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.

 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.

 About

A little about me, and what this page will be about from now on.

 User friendly apps, Dialogs part 1

In this first article about how to design user friendly apps we will discuss the use of Dialogs.

 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

Page 1 / 2

 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.

 QuickTip: PayPal IPN - Complex Pass Through Data

Send complex data in the custom field that you use to match a payment with a customer, order or whatever you need.

 Would this interest you?

Page 1 / 11