Doing HTTP POST with the current SDK

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

Doing HTTP POST with the current SDK

Postby Moons » Thu Apr 23, 2009 8:35 am

First of all, I want to thank plusminus for all the work he's done.

I was looking forward to HTTP POST data from my android app with the current SDK, and actually it is pretty simple :

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4. public void MyFunction{
  5.  
  6.                 HttpClient httpclient = new DefaultHttpClient();
  7.  
  8.                 //Your URL
  9.  
  10.                 HttpPost httppost = new HttpPost("http://www.myurl.com/script.php");
  11.  
  12.  
  13.  
  14.                 try {
  15.  
  16.                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
  17.  
  18.                         //Your DATA
  19.  
  20.                         nameValuePairs.add(new BasicNameValuePair("id", "12345"));
  21.  
  22.                         nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
  23.  
  24.  
  25.  
  26.                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  27.  
  28.  
  29.  
  30.                         HttpResponse response;
  31.  
  32.                         response=httpclient.execute(httppost);
  33.  
  34.                 } catch (ClientProtocolException e) {
  35.  
  36.                         // TODO Auto-generated catch block
  37.  
  38.                         e.printStackTrace();
  39.  
  40.                 } catch (IOException e) {
  41.  
  42.                         // TODO Auto-generated catch block
  43.  
  44.                         e.printStackTrace();
  45.  
  46.                 }
  47.  
  48. }
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


And here it is!
Moons
Developer
Developer
 
Posts: 25
Joined: Fri Feb 13, 2009 9:19 pm

Top

Refactored

Postby wadael » Tue May 26, 2009 8:45 pm

HI Moons,

Thanks a lot for your code, you saved me time as I'm new to Android.
I did some refactoring so that it can be used and reused in one's projects.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package org.wadael.android.utils.net;
  3.  
  4.  
  5.  
  6. import java.io.IOException;
  7.  
  8. import java.util.ArrayList;
  9.  
  10. import java.util.Iterator;
  11.  
  12. import java.util.List;
  13.  
  14. import java.util.Map;
  15.  
  16.  
  17.  
  18. import org.apache.http.HttpResponse;
  19.  
  20. import org.apache.http.NameValuePair;
  21.  
  22. import org.apache.http.client.ClientProtocolException;
  23.  
  24. import org.apache.http.client.HttpClient;
  25.  
  26. import org.apache.http.client.entity.UrlEncodedFormEntity;
  27.  
  28. import org.apache.http.client.methods.HttpPost;
  29.  
  30. import org.apache.http.impl.client.DefaultHttpClient;
  31.  
  32. import org.apache.http.message.BasicNameValuePair;
  33.  
  34. /**
  35.  
  36.  * A refactoring of the code provided by Moons on this page
  37.  
  38.  * http://www.anddev.org/doing_http_post_w ... t5911.html
  39.  
  40.  *
  41.  
  42.  * Allows to send POST requests to a configurable server
  43.  
  44.  *
  45.  
  46.  * @author Moons, Wadael
  47.  
  48.  *
  49.  
  50.  */
  51.  
  52. public class HTTPPoster {
  53.  
  54.  
  55.  
  56.         public static HttpResponse doPost(String url, Map<String, String> kvPairs)
  57.  
  58.                         throws ClientProtocolException, IOException {
  59.  
  60.                 HttpClient httpclient = new DefaultHttpClient();
  61.  
  62.                 HttpPost httppost = new HttpPost(url);
  63.  
  64.  
  65.  
  66.                 if (kvPairs != null && kvPairs.isEmpty() == false) {
  67.  
  68.                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
  69.  
  70.                                         kvPairs.size());
  71.  
  72.                         String k, v;
  73.  
  74.                         Iterator<String> itKeys = kvPairs.keySet().iterator();
  75.  
  76.                         while (itKeys.hasNext()) {
  77.  
  78.                                 k = itKeys.next();
  79.  
  80.                                 v = kvPairs.get(k);
  81.  
  82.                                 nameValuePairs.add(new BasicNameValuePair(k, v));
  83.  
  84.                         }
  85.  
  86.                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  87.  
  88.                 }
  89.  
  90.                 HttpResponse response;
  91.  
  92.                 response = httpclient.execute(httppost);
  93.  
  94.                 return response;
  95.  
  96.         }
  97.  
  98.  
  99.  
  100. }
  101.  
  102.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Usage : in the onClick of a button.
SERVER is a URI constant (="http://.......")

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public void onClick(View v) {
  3.  
  4.                                 String url = SERVER.toASCIIString();
  5.  
  6.                                 Map<String, String> kvPairs = new HashMap<String, String>();
  7.  
  8.                                
  9.  
  10.                                 kvPairs.put("key1","value1");
  11.  
  12.                                 kvPairs.put("key2","value2");
  13.  
  14.                                
  15.  
  16.                                 try {
  17.  
  18.                                         HttpResponse re = HTTPPoster.doPost(url, kvPairs);
  19.  
  20.                                 } catch (ClientProtocolException e) {
  21.  
  22.                                         e.printStackTrace();
  23.  
  24.                                 } catch (IOException e) {
  25.  
  26.                                         e.printStackTrace();
  27.  
  28.                                         // Do something
  29.  
  30.                                 }
  31.  
  32.                         }
  33.  
  34.  
  35.  
  36.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
wadael
Freshman
Freshman
 
Posts: 3
Joined: Tue May 26, 2009 8:09 pm
Location: FR

Postby wadael » Tue May 26, 2009 9:43 pm

Now, if anybody knows how to retreive the content of the response, that would be good :D
wadael
Freshman
Freshman
 
Posts: 3
Joined: Tue May 26, 2009 8:09 pm
Location: FR

Postby kali » Tue Jun 02, 2009 6:34 am

hai moons,
would you teach me how whole code is working with complete samplecode.

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

Postby blade » Sat Jun 06, 2009 8:56 am

@wadael

I found solution here - gotta give man credits for this.

Anyway, it seem that code below would do the trick
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. temp1 = EntityUtils.toString(httpResponse.getEntity());
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


I used the code Moons supplied and added the code above and it works...
blade
Freshman
Freshman
 
Posts: 4
Joined: Wed May 20, 2009 9:16 am

HttpREsponse is richer

Postby wadael » Sat Jun 06, 2009 9:45 pm

Hi Blade,

Thanks for your post. I had tried it before, and it didn't work so I retried.
My pblm was in my code answering to the POST request :(


I've added this method to my class
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. ublic static String getPOSTResponse(String url, Map<String, String> kvPairs) throws ....
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


But finally, I will not use it.
I'd advise you to use the method returning the HttpResponse as it leaves open the posssibility to use the status code (404 ? 200, 500 ?) between other possibilities.

Because one should not assume that the network is reliable.

Thanks.

Jerome
wadael
Freshman
Freshman
 
Posts: 3
Joined: Tue May 26, 2009 8:09 pm
Location: FR

Top

Postby blade » Mon Jun 08, 2009 12:03 pm

Variable httpResponse is actually of type HttpResponse...

You can get HTTP Status Code by using:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. int statusCode = httpResponse.getStatusLine().getStatusCode();
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
blade
Freshman
Freshman
 
Posts: 4
Joined: Wed May 20, 2009 9:16 am

hi

Postby androiddev53 » Wed Jun 17, 2009 4:39 am

I am trying to post an url, for example http://www.google.com & fetch the page.How can I do it on android 1.5?
can somebody guide me with it?

Thanks & Regards,
androiddev53
androiddev53
Freshman
Freshman
 
Posts: 4
Joined: Tue May 19, 2009 2:14 pm

Postby vegolath » Mon Aug 03, 2009 8:23 pm

Well, i decided to combine the the code above with the code from plusminus's tutorial (Thanks)-
Doing HTTP Post with Android (sorry for not adding the actually url, the form engine doesn't let me), to make it supported by the current sdk. Note that instead of using Notification Manager I used a simple text view (cus I'm lazy):


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.vegolath.getandposttest;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.DefaultHttpClient;
  16. import org.apache.http.message.BasicNameValuePair;
  17. import org.apache.http.util.ByteArrayBuffer;
  18.  
  19. import android.app.Activity;
  20. import android.os.Bundle;
  21. import android.widget.TextView;
  22.  
  23. public class GetAndPost extends Activity {
  24.    
  25.         TextView tv;
  26.         String text;
  27.        
  28.     @Override
  29.     public void onCreate(Bundle savedInstanceState) {
  30.         super.onCreate(savedInstanceState);
  31.         setContentView(R.layout.main);
  32.        
  33.         tv = (TextView)findViewById(R.id.textveiw);
  34.         text = "";
  35.        
  36.         postData();
  37.     }
  38.    
  39.     public void postData(){  
  40.        
  41.                     // Create a new HttpClient and Post Header  
  42.                     HttpClient httpclient = new DefaultHttpClient();  
  43.                     HttpPost httppost = new HttpPost("http://www.anddev.org/postresponse.php");  
  44.  
  45.                 try {  
  46.                         // Add your data  
  47.                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
  48.                         nameValuePairs.add(new BasicNameValuePair("mydata", "Mek Mek"));    
  49.                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
  50.        
  51.                         // Execute HTTP Post Request  
  52.                         HttpResponse response = httpclient.execute(httppost);
  53.                        
  54.                         InputStream is = response.getEntity().getContent();
  55.                         BufferedInputStream bis = new BufferedInputStream(is);
  56.                         ByteArrayBuffer baf = new ByteArrayBuffer(20);
  57.  
  58.                          int current = 0;  
  59.                          while((current = bis.read()) != -1){  
  60.                                 baf.append((byte)current);  
  61.                          }  
  62.                            
  63.                         /* Convert the Bytes read to a String. */  
  64.                         text = new String(baf.toByteArray());
  65.                         tv.setText(text);
  66.        
  67.                 } catch (ClientProtocolException e) {  
  68.                         // TODO Auto-generated catch block  
  69.                 } catch (IOException e) {  
  70.                         // TODO Auto-generated catch block  
  71.                 }  
  72.         }
  73. }
Parsed in 0.047 seconds, using GeSHi 1.0.8.4


Thanks!
Attachments
get and post test success.png
get and post test success.png (6.85 KiB) Viewed 22369 times
vegolath
Freshman
Freshman
 
Posts: 2
Joined: Sun Mar 29, 2009 2:53 pm

Postby sandis84 » Wed Aug 26, 2009 8:13 pm

Very nice tutorial, thanks! I have got it working with posting to a server and getting reply. However I fail to add any content when posting to a form. I simply post "null". Could someone explain how to post to this form:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.     <form action="/sign" method="post">
  2.  
  3.       <div><textarea name="content" rows="3" cols="60"></textarea></div>
  4.  
  5.       <div><input type="submit" value="Post Greeting" /></div>
  6.  
  7.     </form>
  8.  
  9.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4
sandis84
Experienced Developer
Experienced Developer
 
Posts: 78
Joined: Fri Aug 07, 2009 3:54 pm

Postby Ressor » Wed Oct 14, 2009 11:53 pm

I'm just starting out and need a little basic help. I've been able to create the HelloAndriod test applicaiton so at least I'm that far, but when I cut and past Vegolath's code into the getandposttest.java file in src on my exclipse dev environment project, I get errors on a few lines. I'm not sure if this code should go into the main .java file and overwrite it all under src or be added as another file.

The errors I see are for the lines below:

Line: public class GetAndPost extends Activity
Error: The public type GetAndPost must be defined in its own file

Line: tv = (TextView)findViewById(R.id.textveiw);
Error: R.id cannot be resolved

Thank you for your patiences and help...
Ressor
Developer
Developer
 
Posts: 28
Joined: Wed Oct 14, 2009 11:43 pm
Location: Boston MA USA

Postby Ressor » Thu Oct 15, 2009 12:32 am

Ok...resolved the first error by changing the .java file name to match the public class.

Still can't figure out the other syntax error listed above.
Ressor
Developer
Developer
 
Posts: 28
Joined: Wed Oct 14, 2009 11:43 pm
Location: Boston MA USA

Postby burakkilic » Fri Oct 16, 2009 4:10 pm

Thanks for this. Now I am trying to read an xml file into a string and Post that string. How can I achieve this?
burakkilic
Developer
Developer
 
Posts: 37
Joined: Thu Oct 01, 2009 10:24 am

Postby wander » Sat Feb 06, 2010 8:19 pm

hi , vegolath.
if i want post the mail and password to https://mail.google.com/mail/x/ .and fetch current account mail subject list...how to do it?

like this:you can see the style on android display .
how_to_do_fetch_gmail_subject_list-t10862.html
wander
Freshman
Freshman
 
Posts: 4
Joined: Sat Jan 30, 2010 9:56 pm

Postby mwq27 » Wed Feb 17, 2010 6:55 pm

vegolath wrote:Well, i decided to combine the the code above with the code from plusminus's tutorial (Thanks)-
Doing HTTP Post with Android (sorry for not adding the actually url, the form engine doesn't let me), to make it supported by the current sdk. Note that instead of using Notification Manager I used a simple text view (cus I'm lazy):


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.vegolath.getandposttest;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.DefaultHttpClient;
  16. import org.apache.http.message.BasicNameValuePair;
  17. import org.apache.http.util.ByteArrayBuffer;
  18.  
  19. import android.app.Activity;
  20. import android.os.Bundle;
  21. import android.widget.TextView;
  22.  
  23. public class GetAndPost extends Activity {
  24.    
  25.         TextView tv;
  26.         String text;
  27.        
  28.     @Override
  29.     public void onCreate(Bundle savedInstanceState) {
  30.         super.onCreate(savedInstanceState);
  31.         setContentView(R.layout.main);
  32.        
  33.         tv = (TextView)findViewById(R.id.textveiw);
  34.         text = "";
  35.        
  36.         postData();
  37.     }
  38.    
  39.     public void postData(){  
  40.        
  41.                     // Create a new HttpClient and Post Header  
  42.                     HttpClient httpclient = new DefaultHttpClient();  
  43.                     HttpPost httppost = new HttpPost("http://www.anddev.org/postresponse.php");  
  44.  
  45.                 try {  
  46.                         // Add your data  
  47.                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
  48.                         nameValuePairs.add(new BasicNameValuePair("mydata", "Mek Mek"));    
  49.                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
  50.        
  51.                         // Execute HTTP Post Request  
  52.                         HttpResponse response = httpclient.execute(httppost);
  53.                        
  54.                         InputStream is = response.getEntity().getContent();
  55.                         BufferedInputStream bis = new BufferedInputStream(is);
  56.                         ByteArrayBuffer baf = new ByteArrayBuffer(20);
  57.  
  58.                          int current = 0;  
  59.                          while((current = bis.read()) != -1){  
  60.                                 baf.append((byte)current);  
  61.                          }  
  62.                            
  63.                         /* Convert the Bytes read to a String. */  
  64.                         text = new String(baf.toByteArray());
  65.                         tv.setText(text);
  66.        
  67.                 } catch (ClientProtocolException e) {  
  68.                         // TODO Auto-generated catch block  
  69.                 } catch (IOException e) {  
  70.                         // TODO Auto-generated catch block  
  71.                 }  
  72.         }
  73. }
Parsed in 0.047 seconds, using GeSHi 1.0.8.4


Thanks!


I am running into a small problem. The code runs correctly and doesnt show any errors, but nothing is posting on the screen. It just stays black, I think theres something wrong with my main.xml file, Im new to this so what should my textview look like?
heres my textview:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor = "#fff"
/>
Thanks
mwq27
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Feb 16, 2010 3:55 pm

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests