Doing HTTP Post with Android

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

Postby andbot » Wed Feb 04, 2009 12:57 pm

so these three packages does not support the current version of SDK.

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

I am darn pretty new to Android/Java. But ever since I got my G1 I have just been dying to code on an app that can POST and GET info from a web app (running apache/php/mysql).

So can some one point me somewhere.

What I want is the user to enter a value in an input box and its POSTed to my server and server sends back reply and its printed on the screen. Now I know this very simple and straight forward stuff.
andbot
Freshman
Freshman
 
Posts: 2
Joined: Wed Feb 04, 2009 12:53 pm

Top

Postby teominator » Thu Feb 05, 2009 7:25 pm

Yes this would be very interesting to know.. I'm also trying to use your tutorial but i can't find RequestQueue, not even in the docs.
teominator
Freshman
Freshman
 
Posts: 6
Joined: Fri Sep 26, 2008 8:56 pm

Postby horse » Sun Feb 08, 2009 3:55 am

I couldnt get it working either, seems SDK 1.0 has made these out of date

I found something here which does the trick

http://blog.richstern.com/?p=32
horse
Freshman
Freshman
 
Posts: 2
Joined: Sat Feb 07, 2009 8:30 pm

Postby Moons » Wed Apr 22, 2009 5:33 pm

So how do we POST data with the current SDK?
Moons
Developer
Developer
 
Posts: 25
Joined: Fri Feb 13, 2009 9:19 pm

Postby songotho » Thu Apr 23, 2009 12:59 pm

Hi, everyone.

I'll try to run app so it's error. It's the same question with andbot: three packages does not support the current version of SDK.
import android.net.http.EventHandler;
import android.net.http.Headers;
import android.net.http.RequestQueue;

How can I import some packages?

Thanks,

--Alex
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Postby Moons » Thu Apr 23, 2009 1:18 pm

These packages are not in the current SDK, here is how you can POST : doing_http_post_with_the_current_sdk-t5911.html
Moons
Developer
Developer
 
Posts: 25
Joined: Fri Feb 13, 2009 9:19 pm

Top

Postby songotho » Thu Apr 23, 2009 1:23 pm

Hi,

I can see in the other apps, they use some packages the same. So How can I run those app?

Thanks,

--Alex
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Postby kali » Tue Jun 02, 2009 7:09 am

hello plusminus,
i read complete tutoral
when i run the code i get error over statement:

android.net.http.RequestQueue rQueue = new RequestQueue(this);

i cnat resolve it. would you have any idea bout this error.

the error is : multiple maker at this line
android.net.http.RequestQueue cannot be resolved
to a type

pls help me.
kali
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Tue Jan 27, 2009 1:31 pm

Problem doing HTTP_PSOT

Postby vishksin » Tue Feb 02, 2010 6:49 am

Hi Plus Minus,

I saw your sample code.

I am running Apache Server in my pc.

I created a very small PHP script which will take input.

PHP Script
<?php
echo "POSTed data: '".$_POST['mydata']."'";
?>
Location of the PHP File:
http://localhost/postresponse.php

I wrote few lines of code to Post HTTP Request with String Info:
package http.pack;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.Activity;
import android.os.Bundle;

public class http_sample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String POSTText = null;
try {
POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
doPost("http://localhost/postresponse.php", POSTText);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private InputStream doPost(String urlString, String content) throws IOException {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = null;
OutputStream out;
byte[] buff;
con.setRequestMethod("POST");
URLConnection.setDefaultRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
out = con.getOutputStream();
buff = content.getBytes("UTF8");
out.write(buff);
out.flush();
out.close();
in = con.getInputStream();
return in;
}
}

Now I get exception error when con.connect(); is hit.
Am I suppose include some thing more.

Please guide me to run this code successfully.

Vishal
vishksin
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Feb 02, 2010 6:19 am

Re: Doing HTTP Post with Android

Postby dj_4war » Fri Apr 09, 2010 4:33 am

Could u pls tell me where can i find android.net.http.RequestQueue api...i am getting error...while creating requestQueue..Like the android.net.http.RequestQueue was not found...also for Header and Iterrator in worker class

also giving error @ Iterator and header class...

also provide code... for geting the response from servlet...instead of PHP...

this could be a really help fr me...




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. 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:
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.033 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.031 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.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
dj_4war
Junior Developer
Junior Developer
 
Posts: 10
Joined: Thu Apr 01, 2010 7:49 am

Re: Doing HTTP Post with Android

Postby songotho » Fri Apr 09, 2010 4:38 am

dj_4war wrote:Could u pls tell me where can i find android.net.http.RequestQueue api...i am getting error...while creating requestQueue..Like the android.net.http.RequestQueue was not found...also for Header and Iterrator in worker class

also giving error @ Iterator and header class...

also provide code... for geting the response from servlet...instead of PHP...

this could be a really help fr me...


U can see the link follow:
Code: Select all
http://android.git.kernel.org/?p=platform/frameworks/base.git;a=tree;f=core/java/android/net/http
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Re: Doing HTTP Post with Android

Postby joellesba » Tue Nov 16, 2010 10:04 pm

I need some help. I have a toggle button on/off, all I want it to do is read on or off on my localhost webpage. I did the internet permission in the manifest and created the button in main.xml, here is my java code, all I want is the webpage to simply read On or Off depending on the button push. I'm begging for help, I read through this forum and tried everything and nothing worked, hence the unused imports... Please help!!!!
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.Menu1;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.ClientProtocolException;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.ResponseHandler;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.BasicResponseHandler;
  16. import org.apache.http.impl.client.DefaultHttpClient;
  17. import org.apache.http.message.BasicNameValuePair;
  18.  
  19. import android.app.Activity;
  20. import android.os.Bundle;
  21. import android.view.View;
  22. import android.widget.Toast;
  23. import android.widget.ToggleButton;
  24.  
  25. public class success extends Activity {
  26.         @Override
  27.         public void onCreate(Bundle savedInstanceState) {
  28.                 super.onCreate(savedInstanceState);
  29.                 setContentView(R.layout.success);
  30.  
  31.                 final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
  32.                 togglebutton.setOnClickListener(new View.OnClickListener() {
  33.                     public void onClick(View v) {
  34.                         // Perform action on clicks
  35.                         if (togglebutton.isChecked()) {
  36.                             Toast.makeText(success.this, "The fuel cell is on", Toast.LENGTH_LONG).show();
  37.                        
  38.                        
  39.                         } else {
  40.                             Toast.makeText(success.this, "The fuel cell is off", Toast.LENGTH_LONG).show();
  41.                    
  42.                        
  43.                         }
  44.                     }
  45.                 });
  46.                
  47.         }
  48.          
  49.                
  50.         }
  51.  
Parsed in 0.043 seconds, using GeSHi 1.0.8.4
joellesba
Freshman
Freshman
 
Posts: 7
Joined: Mon Nov 15, 2010 10:59 pm

Re: Doing HTTP Post with Android

Postby z12ent » Mon Mar 14, 2011 5:16 pm

Great tutorial! I'm a newbee so please bare with me, I'm wondering how would one be able to create a custom ListView with images and strings using this method? Do you have an example of something like that? :D
z12ent
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Mar 14, 2011 5:13 pm

Re: Doing HTTP Post with Android

Postby wakawaka » Sun Apr 17, 2011 2:15 pm

Thanks. It helped me lot.
Android Development Tutorials and Code Snippets: http://forum.gssdaily.com/
wakawaka
Experienced Developer
Experienced Developer
 
Posts: 79
Joined: Tue Jan 11, 2011 1:51 pm

Re: Doing HTTP Post with Android

Postby AndroidNewbie:) » Mon Sep 12, 2011 5:37 am

songotho wrote:
dj_4war wrote:Could u pls tell me where can i find android.net.http.RequestQueue api...i am getting error...while creating requestQueue..Like the android.net.http.RequestQueue was not found...also for Header and Iterrator in worker class

also giving error @ Iterator and header class...

also provide code... for geting the response from servlet...instead of PHP...

this could be a really help fr me...


U can see the link follow:
Code: Select all
http://android.git.kernel.org/?p=platform/frameworks/base.git;a=tree;f=core/java/android/net/http


i've got same problem :D
i can't get solution at the link. can someone help me ?
AndroidNewbie:)
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Sep 12, 2011 5:12 am

Top
Previous

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests