Doing HTTP Post with Android

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Postby cyberrob » Thu Feb 14, 2008 9:45 am

Hi Plusminus,
The NotificationManager in the sample code, sad to say that new SDK m5 not support it!

Notification Manager:

* Transient notifications are not called notifications anymore. They are now called android.widget.Toasts. This name may not be permanent, but the rest of the API should be quite settledTransient notifications are not called notifications anymore. They are now called android.widget.Toasts. This name may not be permanent, but the rest of the API should be quite settled.
User avatar
cyberrob
Junior Developer
Junior Developer
 
Posts: 12
Joined: Thu Dec 13, 2007 3:01 am

Top

Postby plusminus » Thu Feb 14, 2008 9:54 am

cyberrob wrote:Hi Plusminus,
The NotificationManager in the sample code, sad to say that new SDK m5 not support it!


I know, all Tutorials have to be adapted :shock: :shock: :shock:

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby chouputra » Wed Feb 20, 2008 8:38 am

Very nice work plusminus, I have been creating my own thread to do HTTP posting and with this it would makes it easier to code.
chouputra
Junior Developer
Junior Developer
 
Posts: 10
Joined: Wed Feb 20, 2008 3:44 am
Location: Jakarta, Indonesia

Postby kiran » Tue Mar 11, 2008 8:12 am

Hi,

I tried to implement the HTTP Post example in m5. After small modifications, running the code gives me an error message "Can't create handler inside thread that has not called Looper.prepare()".

Pls help me.

Thanks in advance.
:) smile it is the key that fits the lock of everybody's heart
User avatar
kiran
Experienced Developer
Experienced Developer
 
Posts: 78
Joined: Thu Nov 22, 2007 11:36 am
Location: India

Regarding http post

Postby Raju » Thu Mar 20, 2008 9:55 am

Hi ,
I tried the HTTP Post method and its really working fine...Thanks to all ....

but i m getting a null pointer exception at rQUEUE.waituntillcomplete(), when trying to send a request when there is no network connection.....
this is the log :

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. D/dalvikvm( 1133): Exception Ljava/lang/NullPointerException; from Connection.java:537 not caught locally
  2.  
  3. W/dalvikvm( 1133): threadid=19: thread exiting with uncaught exception (group=0x4000fdf8)
  4.  
  5. E/AndroidRuntime( 1133): Uncaught handler: thread abc.com:443 exiting due to uncaught exception
  6.  
  7. E/AndroidRuntime( 1133): java.lang.NullPointerException
  8.  
  9. E/AndroidRuntime( 1133):        at android.net.http.Connection.httpFailure(Connection.java:537)
  10.  
  11. E/AndroidRuntime( 1133):        at android.net.http.Connection.processRequests(Connection.java:318)
  12.  
  13. E/AndroidRuntime( 1133):        at android.net.http.ConnectionThread.run(Connection.java:674)
  14.  
  15. I/Process (  525): Sending signal. PID: 1133 SIG: 3
  16.  
  17. I/dalvikvm( 1133): threadid=7: reacting to signal 3
  18.  
  19. I/dalvikvm( 1133): DALVIK THREADS:
  20.  
  21. I/dalvikvm( 1133): "Main" prio=5 tid=3 WAIT
  22.  
  23. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x40010450
  24.  
  25. I/dalvikvm( 1133):   | sysTid=506 nice=0 sched=0/0 handle=-1098887940
  26.  
  27. I/dalvikvm( 1133):   at java.lang.Object.wait(Native Method)
  28.  
  29. I/dalvikvm( 1133):   at java.lang.Object.wait(Object.java:195)
  30.  
  31. I/dalvikvm( 1133):   at android.os.MessageQueue.next(MessageQueue.java:137)
  32.  
  33. I/dalvikvm( 1133):   at android.os.Looper.loop(Looper.java:79)
  34.  
  35. I/dalvikvm( 1133):   at android.app.ActivityThread.main(ActivityThread.java:3052)
  36.  
  37. I/dalvikvm( 1133):   (break frame)
  38.  
  39. I/dalvikvm( 1133):   at java.lang.reflect.Method.invokeNative(Native Method)
  40.  
  41. I/dalvikvm( 1133):   at java.lang.reflect.Method.invoke(Method.java:356)
  42.  
  43. I/dalvikvm( 1133):   at android.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1547)
  44.  
  45. I/dalvikvm( 1133):   at android.os.ZygoteInit.main(ZygoteInit.java:1445)
  46.  
  47. I/dalvikvm( 1133):   (break frame)
  48.  
  49. I/dalvikvm( 1133):   at android.dalvik.NativeStart.main(Native Method)
  50.  
  51. I/dalvikvm( 1133):   (break frame)
  52.  
  53. I/dalvikvm( 1133):
  54.  
  55. I/dalvikvm( 1133): "abc:443" prio=5 tid=19 NATIVE
  56.  
  57. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x40328710
  58.  
  59. I/dalvikvm( 1133):   | sysTid=1663 nice=0 sched=0/0 handle=2197640
  60.  
  61. I/dalvikvm( 1133):   at android.os.BinderProxy.transact(Native Method)
  62.  
  63. I/dalvikvm( 1133):   at android.app.ActivityManagerProxy.handleApplicationError(ActivityManagerNative.java:1441)
  64.  
  65. I/dalvikvm( 1133):   at android.os.RuntimeInit.crash(RuntimeInit.java:250)
  66.  
  67. I/dalvikvm( 1133):   at android.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:56)
  68.  
  69. I/dalvikvm( 1133):   at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:853)
  70.  
  71. I/dalvikvm( 1133):   at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:850)
  72.  
  73. I/dalvikvm( 1133):   (break frame)
  74.  
  75. I/dalvikvm( 1133):
  76.  
  77. I/dalvikvm( 1133): "Thread-25" prio=5 tid=17 WAIT
  78.  
  79. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x4044f350
  80.  
  81. I/dalvikvm( 1133):   | sysTid=1655 nice=0 sched=0/0 handle=2195624
  82.  
  83. I/dalvikvm( 1133):   at java.lang.Object.wait(Native Method)
  84.  
  85. I/dalvikvm( 1133):   - waiting on <0x158e18> (a android.net.http.RequestQueue)
  86.  
  87. I/dalvikvm( 1133):   at java.lang.Object.wait(Object.java:170)
  88.  
  89. I/dalvikvm( 1133):   at android.net.http.RequestQueue.waitUntilComplete(RequestQueue.java:325)
  90.  
  91. I/dalvikvm( 1133):   at com.google.android.sm.HttpPost.go(HttpPost.java:147)
  92.  
  93. I/dalvikvm( 1133):   at com.google.android.sm.HTTPRequest.get(HTTPRequest.java:506)
  94.  
  95. I/dalvikvm( 1133):   at com.google.android.sm.viewList$6.run(viewList.java:1608)
  96.  
  97. I/dalvikvm( 1133):   (break frame)
  98.  
  99. I/dalvikvm( 1133):
  100.  
  101. I/dalvikvm( 1133): "Binder Thread #3" prio=5 tid=15 NATIVE
  102.  
  103. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x401ca588
  104.  
  105. I/dalvikvm( 1133):   | sysTid=1184 nice=-10 sched=0/0 handle=1165512
  106.  
  107. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  108.  
  109. I/dalvikvm( 1133):   (break frame)
  110.  
  111. I/dalvikvm( 1133):
  112.  
  113. I/dalvikvm( 1133): "Binder Thread #2" prio=5 tid=13 NATIVE
  114.  
  115. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x4001a1d0
  116.  
  117. I/dalvikvm( 1133):   | sysTid=1141 nice=-10 sched=0/0 handle=1317888
  118.  
  119. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  120.  
  121. I/dalvikvm( 1133):   (break frame)
  122.  
  123. I/dalvikvm( 1133):
  124.  
  125. I/dalvikvm( 1133): "Binder Thread #1" prio=5 tid=11 NATIVE
  126.  
  127. I/dalvikvm( 1133):   | group="main" sCount=1 dsCount=0 s=0 obj=0x40019080
  128.  
  129. I/dalvikvm( 1133):   | sysTid=1140 nice=-10 sched=0/0 handle=1314584
  130.  
  131. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  132.  
  133. I/dalvikvm( 1133):   (break frame)
  134.  
  135. I/dalvikvm( 1133):
  136.  
  137. I/dalvikvm( 1133): "JDWP" daemon prio=5 tid=9 VMWAIT
  138.  
  139. I/dalvikvm( 1133):   | group="system" sCount=1 dsCount=0 s=0 obj=0x4005eaf0
  140.  
  141.                                                                                                            35,1          65%
  142.  
  143. I/dalvikvm( 1133): "JDWP" daemon prio=5 tid=9 VMWAIT
  144.  
  145. I/dalvikvm( 1133):   | group="system" sCount=1 dsCount=0 s=0 obj=0x4005eaf0
  146.  
  147. I/dalvikvm( 1133):   | sysTid=1136 nice=0 sched=0/0 handle=1311144
  148.  
  149. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  150.  
  151. I/dalvikvm( 1133):   (break frame)
  152.  
  153. I/dalvikvm( 1133):  
  154.  
  155. I/dalvikvm( 1133): "Signal Catcher" daemon prio=5 tid=7 RUNNABLE
  156.  
  157. I/dalvikvm( 1133):   | group="system" sCount=0 dsCount=0 s=0 obj=0x40024128
  158.  
  159. I/dalvikvm( 1133):   | sysTid=1135 nice=0 sched=0/0 handle=1300032
  160.  
  161. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  162.  
  163. I/dalvikvm( 1133):   (break frame)
  164.  
  165. I/dalvikvm( 1133):  
  166.  
  167. I/dalvikvm( 1133): "HeapWorker" daemon prio=5 tid=5 VMWAIT
  168.  
  169. I/dalvikvm( 1133):   | group="system" sCount=1 dsCount=0 s=0 obj=0x40022428
  170.  
  171. I/dalvikvm( 1133):   | sysTid=1134 nice=0 sched=0/0 handle=1297432
  172.  
  173. I/dalvikvm( 1133):   at android.dalvik.NativeStart.run(Native Method)
  174.  
  175. I/dalvikvm( 1133):   (break frame)
  176.  
  177. I/dalvikvm( 1133):
Parsed in 0.052 seconds, using GeSHi 1.0.8.4
Raju
Freshman
Freshman
 
Posts: 5
Joined: Mon Dec 17, 2007 1:20 pm

Re: Doing HTTP Post with Android

Postby rohan » Fri Mar 21, 2008 11:33 am

plusminus wrote:
Doing HTTP Post with Android


What you will learn: You will learn how to do HTTP Post from within Android.

:?: Problems/Questions: Write them right below...

Difficulty: 2 of 5 :)

What it will look like:
Image


Description:
0.) HTTP is a request-response protocol. Various types of requests are possible, each identified by a different HTTP method. Her we will use the POST-Method.

1.) So we will once again start, where all Activities start. We will do some simple preparation first:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void onCreate(Bundle icicle) {
  3.                 super.onCreate(icicle);
  4.  
  5.                 /* Create a new HTTP-RequestQueue. */
  6.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  7.                
  8.                 /* Prepare the Post-Text we are going to send. */
  9.                 String POSTText = null;
  10.                 try {
  11.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  12.                 } catch (UnsupportedEncodingException e) {
  13.                         return;
  14.                 }
  15.                 /* And put the encoded bytes into an BAIS,
  16.                  * where a function later can READ bytes from. */
  17.                 byte[] POSTbytes = POSTText.getBytes();
  18.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
Parsed in 0.034 seconds, using GeSHi 1.0.8.4

2.) Preparation is done now, now we will do the interesting stuff:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Create a header-hashmap */
  2.                 Map<String, String> headers = new HashMap<String, String>();
  3.                 /* and put the Default-Encoding for html-forms to it. */
  4.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  5.                
  6.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  7.                 MyEventHandler myEvH = new MyEventHandler(this);
Parsed in 0.035 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:
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1.                  <?php
  2.                                 echo "POSTed data: '".$_POST['mydata']."'";
  3.                  ?>
Parsed in 0.062 seconds, using GeSHi 1.0.8.4

4.) So we will call the queueRequest of our RequestQueue with the following parameters:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. "http://www.anddev.org/postresponse.php",  // The location of the php-file
  2. "POST", // The Request-'Mode'
  3. headers, // The Header which tells we will have some POST-vars
  4. myEvH, // our eventhandler
  5. baos, // our POST-String(converted to bytes) and ready to be sent
  6. POSTbytes.length, // amount of the bytes in 'baos' to be sent
  7. 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:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Calls a php-file I prepared. It looks like:
  2.                  * <?php
  3.                  *              echo "POSTed data: '".$_POST['data']."'";
  4.                  * ?>*/
  5.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  6.                                 headers, myEvH, baos, POSTbytes.length,false);
  7.  
  8.                 /* Wait until the request is complete.*/
  9.                 rQueue.waitUntilComplete();
  10.         }
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:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 public void data(byte[] bytes, int len) {
  2.                         baf.append(bytes, 0, len); // Add received data to a buffer }
  3.  
  4.                 public void endData() {
  5.                         String text = new String(baf.toByteArray()); // Conert Buffer to String
  6.                         myShowNotificationAndLog("Data loaded: n" + text); // Log what was returned }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


Thats it :)


The Full Source:

"/src/your_package_structure/HTTPPostExample.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.webstuff;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.util.HashMap;
  7. import java.util.Iterator;
  8. import java.util.Map;
  9.  
  10. import org.apache.http.util.ByteArrayBuffer;
  11.  
  12. import android.app.Activity;
  13. import android.app.NotificationManager;
  14. import android.net.http.EventHandler;
  15. import android.net.http.Headers;
  16. import android.net.http.RequestQueue;
  17. import android.net.http.SslCertificate;
  18. import android.os.Bundle;
  19. import android.util.Log;
  20.  
  21. public class HTTPPostExample extends Activity {
  22.  
  23.         // ===========================================================
  24.         // Fields
  25.         // ===========================================================
  26.        
  27.         private final String DEBUG_TAG = "httpPostExample";
  28.  
  29.         // ===========================================================
  30.         // 'Constructors'
  31.         // ===========================================================
  32.  
  33.         @Override
  34.         public void onCreate(Bundle icicle) {
  35.                 super.onCreate(icicle);
  36.  
  37.                 /* Create a new HTTP-RequestQueue. */
  38.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  39.                
  40.                 /* Prepare the Post-Text we are going to send. */
  41.                 String POSTText = null;
  42.                 try {
  43.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  44.                 } catch (UnsupportedEncodingException e) {
  45.                         return;
  46.                 }
  47.                 /* And put the encoded bytes into an BAIS,
  48.                  * where a function later can read bytes from. */
  49.                 byte[] POSTbytes = POSTText.getBytes();
  50.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
  51.                
  52.                 /* Create a header-hashmap */
  53.                 Map<String, String> headers = new HashMap<String, String>();
  54.                 /* and put the Default-Encoding for html-forms to it. */
  55.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  56.                
  57.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  58.                 MyEventHandler myEvH = new MyEventHandler(this);
  59.  
  60.                 /* Now we call a php-file I prepared. It is exactly this:
  61.                  * <?php
  62.                  *              echo "POSTed data: '".$_POST['data']."'";
  63.                  * ?>*/
  64.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  65.                                 headers, myEvH, baos, POSTbytes.length,false);
  66.  
  67.                 /* Wait until the request is complete.*/
  68.                 rQueue.waitUntilComplete();
  69.         }
  70.        
  71.         // ===========================================================
  72.         // Worker Class
  73.         // ===========================================================
  74.        
  75.         private class MyEventHandler implements EventHandler {
  76.                 private static final int RANDOM_ID = 0x1337;
  77.  
  78.                 /** Will hold the data returned by the URLCall. */
  79.                 ByteArrayBuffer baf = new ByteArrayBuffer(20);
  80.                
  81.                 /** Needed, as we want to show the results as Notifications. */
  82.                 private Activity myActivity;
  83.  
  84.                 MyEventHandler(Activity activity) {
  85.                         this.myActivity = activity;  }
  86.  
  87.                 public void data(byte[] bytes, int len) {
  88.                         baf.append(bytes, 0, len);  }
  89.  
  90.                 public void endData() {
  91.                         String text = new String(baf.toByteArray());
  92.                         myShowNotificationAndLog("Data loaded: n" + text);  }
  93.  
  94.                 public void status(int arg0, int arg1, int arg2, String s) {
  95.                         myShowNotificationAndLog("status [" + s + "]");  }
  96.  
  97.                 public void error(int i, String s) {
  98.                         this.myShowNotificationAndLog("error [" + s + "]");  }
  99.  
  100.                 public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
  101.                 public void headers(Iterator arg0) { }
  102.                 public void headers(Headers arg0) { }
  103.  
  104.                 private void myShowNotificationAndLog(String msg) {
  105.                         /* Print msg to LogCat and show Notification. */
  106.                         Log.d(DEBUG_TAG, msg);
  107.                         NotificationManager nm = (NotificationManager) this.myActivity
  108.                                         .getSystemService(Activity.NOTIFICATION_SERVICE);
  109.                         nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);
  110.                 }
  111.         }
  112. }
Parsed in 0.050 seconds, using GeSHi 1.0.8.4


Regards,
plusminus


Hi Plusminus,
I have created a new project for this Http post, but i am gettin an error in the last line (I have taken your above code) "nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);"....there is no method named "notifyWithText()". What should i do ? please help.. I am using new SDK(m5)
Thanx.
Last edited by rohan on Sun Mar 23, 2008 8:46 am, edited 1 time in total.
rohan
Developer
Developer
 
Posts: 34
Joined: Wed Mar 19, 2008 2:26 pm

Top

Re: Doing HTTP Post with Android

Postby rohan » Sun Mar 23, 2008 6:54 am

plusminus wrote:
Doing HTTP Post with Android


What you will learn: You will learn how to do HTTP Post from within Android.

:?: Problems/Questions: Write them right below...

Difficulty: 2 of 5 :)

What it will look like:
Image


Description:
0.) HTTP is a request-response protocol. Various types of requests are possible, each identified by a different HTTP method. Her we will use the POST-Method.

1.) So we will once again start, where all Activities start. We will do some simple preparation first:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void onCreate(Bundle icicle) {
  3.                 super.onCreate(icicle);
  4.  
  5.                 /* Create a new HTTP-RequestQueue. */
  6.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  7.                
  8.                 /* Prepare the Post-Text we are going to send. */
  9.                 String POSTText = null;
  10.                 try {
  11.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  12.                 } catch (UnsupportedEncodingException e) {
  13.                         return;
  14.                 }
  15.                 /* And put the encoded bytes into an BAIS,
  16.                  * where a function later can READ bytes from. */
  17.                 byte[] POSTbytes = POSTText.getBytes();
  18.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
Parsed in 0.038 seconds, using GeSHi 1.0.8.4

2.) Preparation is done now, now we will do the interesting stuff:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Create a header-hashmap */
  2.                 Map<String, String> headers = new HashMap<String, String>();
  3.                 /* and put the Default-Encoding for html-forms to it. */
  4.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  5.                
  6.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  7.                 MyEventHandler myEvH = new MyEventHandler(this);
Parsed in 0.037 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:
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1.                  <?php
  2.                                 echo "POSTed data: '".$_POST['mydata']."'";
  3.                  ?>
Parsed in 0.060 seconds, using GeSHi 1.0.8.4

4.) So we will call the queueRequest of our RequestQueue with the following parameters:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. "http://www.anddev.org/postresponse.php",  // The location of the php-file
  2. "POST", // The Request-'Mode'
  3. headers, // The Header which tells we will have some POST-vars
  4. myEvH, // our eventhandler
  5. baos, // our POST-String(converted to bytes) and ready to be sent
  6. POSTbytes.length, // amount of the bytes in 'baos' to be sent
  7. false // dunno <img src="http://www.anddev.org/images/smilies/hmm.png" alt=":?" title="Confused" />
Parsed in 0.037 seconds, using GeSHi 1.0.8.4

So as a real implementated call it looks like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Calls a php-file I prepared. It looks like:
  2.                  * <?php
  3.                  *              echo "POSTed data: '".$_POST['data']."'";
  4.                  * ?>*/
  5.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  6.                                 headers, myEvH, baos, POSTbytes.length,false);
  7.  
  8.                 /* Wait until the request is complete.*/
  9.                 rQueue.waitUntilComplete();
  10.         }
Parsed in 0.037 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:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 public void data(byte[] bytes, int len) {
  2.                         baf.append(bytes, 0, len); // Add received data to a buffer }
  3.  
  4.                 public void endData() {
  5.                         String text = new String(baf.toByteArray()); // Conert Buffer to String
  6.                         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"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.webstuff;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.util.HashMap;
  7. import java.util.Iterator;
  8. import java.util.Map;
  9.  
  10. import org.apache.http.util.ByteArrayBuffer;
  11.  
  12. import android.app.Activity;
  13. import android.app.NotificationManager;
  14. import android.net.http.EventHandler;
  15. import android.net.http.Headers;
  16. import android.net.http.RequestQueue;
  17. import android.net.http.SslCertificate;
  18. import android.os.Bundle;
  19. import android.util.Log;
  20.  
  21. public class HTTPPostExample extends Activity {
  22.  
  23.         // ===========================================================
  24.         // Fields
  25.         // ===========================================================
  26.        
  27.         private final String DEBUG_TAG = "httpPostExample";
  28.  
  29.         // ===========================================================
  30.         // 'Constructors'
  31.         // ===========================================================
  32.  
  33.         @Override
  34.         public void onCreate(Bundle icicle) {
  35.                 super.onCreate(icicle);
  36.  
  37.                 /* Create a new HTTP-RequestQueue. */
  38.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  39.                
  40.                 /* Prepare the Post-Text we are going to send. */
  41.                 String POSTText = null;
  42.                 try {
  43.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  44.                 } catch (UnsupportedEncodingException e) {
  45.                         return;
  46.                 }
  47.                 /* And put the encoded bytes into an BAIS,
  48.                  * where a function later can read bytes from. */
  49.                 byte[] POSTbytes = POSTText.getBytes();
  50.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
  51.                
  52.                 /* Create a header-hashmap */
  53.                 Map<String, String> headers = new HashMap<String, String>();
  54.                 /* and put the Default-Encoding for html-forms to it. */
  55.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  56.                
  57.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  58.                 MyEventHandler myEvH = new MyEventHandler(this);
  59.  
  60.                 /* Now we call a php-file I prepared. It is exactly this:
  61.                  * <?php
  62.                  *              echo "POSTed data: '".$_POST['data']."'";
  63.                  * ?>*/
  64.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  65.                                 headers, myEvH, baos, POSTbytes.length,false);
  66.  
  67.                 /* Wait until the request is complete.*/
  68.                 rQueue.waitUntilComplete();
  69.         }
  70.        
  71.         // ===========================================================
  72.         // Worker Class
  73.         // ===========================================================
  74.        
  75.         private class MyEventHandler implements EventHandler {
  76.                 private static final int RANDOM_ID = 0x1337;
  77.  
  78.                 /** Will hold the data returned by the URLCall. */
  79.                 ByteArrayBuffer baf = new ByteArrayBuffer(20);
  80.                
  81.                 /** Needed, as we want to show the results as Notifications. */
  82.                 private Activity myActivity;
  83.  
  84.                 MyEventHandler(Activity activity) {
  85.                         this.myActivity = activity;  }
  86.  
  87.                 public void data(byte[] bytes, int len) {
  88.                         baf.append(bytes, 0, len);  }
  89.  
  90.                 public void endData() {
  91.                         String text = new String(baf.toByteArray());
  92.                         myShowNotificationAndLog("Data loaded: n" + text);  }
  93.  
  94.                 public void status(int arg0, int arg1, int arg2, String s) {
  95.                         myShowNotificationAndLog("status [" + s + "]");  }
  96.  
  97.                 public void error(int i, String s) {
  98.                         this.myShowNotificationAndLog("error [" + s + "]");  }
  99.  
  100.                 public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
  101.                 public void headers(Iterator arg0) { }
  102.                 public void headers(Headers arg0) { }
  103.  
  104.                 private void myShowNotificationAndLog(String msg) {
  105.                         /* Print msg to LogCat and show Notification. */
  106.                         Log.d(DEBUG_TAG, msg);
  107.                         NotificationManager nm = (NotificationManager) this.myActivity
  108.                                         .getSystemService(Activity.NOTIFICATION_SERVICE);
  109.                         nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);
  110.                 }
  111.         }
  112. }
Parsed in 0.051 seconds, using GeSHi 1.0.8.4


Regards,
plusminus


hi plusminus,
Wht modifications shouls i do to run this code on m5 .........
Plz reply

Thanx , ROHAN
rohan
Developer
Developer
 
Posts: 34
Joined: Wed Mar 19, 2008 2:26 pm

HTTP Post

Postby Raju » Mon Mar 24, 2008 11:16 am

Hi PlusMinus....

In the HTTP Post example I am getting null pointer exception when the net connection is not available. Can you please suggest where to handle the exception in the example. Its already 3 days I am trying but in vain. Please suggest how and where to handle the exception. I have already posted my log above.

Regards,
Raju.
Raju
Freshman
Freshman
 
Posts: 5
Joined: Mon Dec 17, 2007 1:20 pm

Getting status of RequestQueue

Postby Obbo » Sun Mar 30, 2008 10:54 am

Hi guys,

thanks for all the info, it's wonderful to see people invest for the greater good :)

I have a question about RequestQueue -
In the example of this post we always call rQueue.waitUntilCompleted() after the request.

I want to call something like rQueue.isCompleted() instead, so my program can continue to function, and only pull the response once it is complete.

With the current information I can write a wrapping class that has a simple response handler which sets up a Completed flag - and then I can check it (the get/set function should be marked synchronized).
But is there something like this already built-in?

From the best of my searches, there isn't, but maybe I'm missing something...

Thanks!
Obbo.
Obbo
Freshman
Freshman
 
Posts: 5
Joined: Sun Mar 30, 2008 10:47 am

Postby kiran » Mon Apr 07, 2008 10:44 am

hi,
how can we handle request time out while using this code. the application hangs when a connection times out. pls help.
Regards,
Kiran.
:) smile it is the key that fits the lock of everybody's heart
User avatar
kiran
Experienced Developer
Experienced Developer
 
Posts: 78
Joined: Thu Nov 22, 2007 11:36 am
Location: India

Postby Raju » Tue Apr 08, 2008 7:58 am

Hi Kiran...

I am also facing the same problem in using requestQueue...Unable to handle the timeout and after some time (if there is no network connection ) a null pointer exception is thrown....Can anybody please help....

Regards,
Raju
Raju
Freshman
Freshman
 
Posts: 5
Joined: Mon Dec 17, 2007 1:20 pm

Postby stilwalli » Wed Aug 06, 2008 1:49 pm

Is multi part response supported in android.
stilwalli
Developer
Developer
 
Posts: 35
Joined: Mon Jul 21, 2008 8:13 am

Postby stilwalli » Wed Aug 06, 2008 2:04 pm

does android support multipart response????????????
stilwalli
Developer
Developer
 
Posts: 35
Joined: Mon Jul 21, 2008 8:13 am

Nice Tutorial, but does it work with the New SDK ???

Postby dhiwakarmani » Thu Sep 25, 2008 1:56 pm

Thanks a lot for the nice tutorial.

Just curious, does this code will work with the new release SDK 1.0 ?

Looking forward for the reply.

Thanks

Regards,

Dhiwakar
dhiwakarmani
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Feb 08, 2008 5:16 am

Postby Surbhit » Wed Nov 19, 2008 8:18 pm

Hi plusminus,

Can you please modify this tutorial as per the current sdk ?

import android.net.http.EventHandler;
import android.net.http.Headers;
import android.net.http.RequestQueue;

Above packages are not there in android. So please tell me an alternative.

Please help........
Surbhit
Freshman
Freshman
 
Posts: 4
Joined: Mon Nov 17, 2008 4:24 pm

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 7 guests