Doing HTTP Post with Android
What you will learn: You will learn how to do HTTP Post from within Android.
Difficulty: 2 of 5

What it will look like:

Description:
0.) HTTP is a request-response protocol. Various types of requests are possible, each identified by a different HTTP method. Here we will use the POST-Method.
1.) So we will once again start, where all Activities start. We will do some simple preparation first:
Using java Syntax Highlighting
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- /* Create a new HTTP-RequestQueue. */
- android.net.http.RequestQueue rQueue = new RequestQueue(this);
- /* Prepare the Post-Text we are going to send. */
- String POSTText = null;
- try {
- POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
- } catch (UnsupportedEncodingException e) {
- return;
- }
- /* And put the encoded bytes into an BAIS,
- * where a function later can READ bytes from. */
- byte[] POSTbytes = POSTText.getBytes();
- ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
2.) Preparation is done now, now we will do the interesting stuff:
Using java Syntax Highlighting
- /* Create a header-hashmap */
- Map<String, String> headers = new HashMap<String, String>();
- /* and put the Default-Encoding for html-forms to it. */
- headers.put("Content-Type", "application/x-www-form-urlencoded");
- /* Create a new EventHandler defined above, to handle what gets returned. */
- MyEventHandler myEvH = new MyEventHandler(this);
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
:idea: MyEventHandler is described in step 5.)
3.) I prepared a very simple php-file on my server, which will simply echo the 'mydata' variable posted to it:
Using php Syntax Highlighting
- <?php
- echo "POSTed data: '".$_POST['mydata']."'";
- ?>
Parsed in 0.061 seconds, using GeSHi 1.0.8.4
4.) So we will call the queueRequest of our RequestQueue with the following parameters:
Using java Syntax Highlighting
- "http://www.anddev.org/postresponse.php", // The location of the php-file
- "POST", // The Request-'Mode'
- headers, // The Header which tells we will have some POST-vars
- myEvH, // our eventhandler
- baos, // our POST-String(converted to bytes) and ready to be sent
- POSTbytes.length, // amount of the bytes in 'baos' to be sent
- false // dunno <img src="http://www.anddev.org/images/smilies/hmm.png" alt=":?" title="Confused" />
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
So as a real implementated call it looks like this:
Using java Syntax Highlighting
- /* Calls a php-file I prepared. It looks like:
- * <?php
- * echo "POSTed data: '".$_POST['data']."'";
- * ?>*/
- rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
- headers, myEvH, baos, POSTbytes.length,false);
- /* Wait until the request is complete.*/
- rQueue.waitUntilComplete();
- }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
5.) The last thing we have is a small nearly dummy-class, the MyEventHandler, which simple reacts on events that occur during the "answer" of the requested url called. There basically are just two functions that actually do something:
Using java Syntax Highlighting
- public void data(byte[] bytes, int len) {
- baf.append(bytes, 0, len); // Add received data to a buffer }
- public void endData() {
- String text = new String(baf.toByteArray()); // Conert Buffer to String
- myShowNotificationAndLog("Data loaded: n" + text); // Log what was returned }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4
Thats it 

The Full Source:
"/src/your_package_structure/HTTPPostExample.java"
Using java Syntax Highlighting
- package org.anddev.android.webstuff;
- import java.io.ByteArrayInputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import org.apache.http.util.ByteArrayBuffer;
- import android.app.Activity;
- import android.app.NotificationManager;
- import android.net.http.EventHandler;
- import android.net.http.Headers;
- import android.net.http.RequestQueue;
- import android.net.http.SslCertificate;
- import android.os.Bundle;
- import android.util.Log;
- public class HTTPPostExample extends Activity {
- // ===========================================================
- // Fields
- // ===========================================================
- private final String DEBUG_TAG = "httpPostExample";
- // ===========================================================
- // 'Constructors'
- // ===========================================================
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- /* Create a new HTTP-RequestQueue. */
- android.net.http.RequestQueue rQueue = new RequestQueue(this);
- /* Prepare the Post-Text we are going to send. */
- String POSTText = null;
- try {
- POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
- } catch (UnsupportedEncodingException e) {
- return;
- }
- /* And put the encoded bytes into an BAIS,
- * where a function later can read bytes from. */
- byte[] POSTbytes = POSTText.getBytes();
- ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
- /* Create a header-hashmap */
- Map<String, String> headers = new HashMap<String, String>();
- /* and put the Default-Encoding for html-forms to it. */
- headers.put("Content-Type", "application/x-www-form-urlencoded");
- /* Create a new EventHandler defined above, to handle what gets returned. */
- MyEventHandler myEvH = new MyEventHandler(this);
- /* Now we call a php-file I prepared. It is exactly this:
- * <?php
- * echo "POSTed data: '".$_POST['data']."'";
- * ?>*/
- rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
- headers, myEvH, baos, POSTbytes.length,false);
- /* Wait until the request is complete.*/
- rQueue.waitUntilComplete();
- }
- // ===========================================================
- // Worker Class
- // ===========================================================
- private class MyEventHandler implements EventHandler {
- private static final int RANDOM_ID = 0x1337;
- /** Will hold the data returned by the URLCall. */
- ByteArrayBuffer baf = new ByteArrayBuffer(20);
- /** Needed, as we want to show the results as Notifications. */
- private Activity myActivity;
- MyEventHandler(Activity activity) {
- this.myActivity = activity; }
- public void data(byte[] bytes, int len) {
- baf.append(bytes, 0, len); }
- public void endData() {
- String text = new String(baf.toByteArray());
- myShowNotificationAndLog("Data loaded: n" + text); }
- public void status(int arg0, int arg1, int arg2, String s) {
- myShowNotificationAndLog("status [" + s + "]"); }
- public void error(int i, String s) {
- this.myShowNotificationAndLog("error [" + s + "]"); }
- public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
- public void headers(Iterator arg0) { }
- public void headers(Headers arg0) { }
- private void myShowNotificationAndLog(String msg) {
- /* Print msg to LogCat and show Notification. */
- Log.d(DEBUG_TAG, msg);
- NotificationManager nm = (NotificationManager) this.myActivity
- .getSystemService(Activity.NOTIFICATION_SERVICE);
- nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);
- }
- }
- }
Parsed in 0.052 seconds, using GeSHi 1.0.8.4
Regards,
plusminus






