andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Doing HTTP POST with the current SDK


 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
Moons
Junior Developer
Junior Developer


Joined: 13 Feb 2009
Posts: 23

PostPosted: Thu Apr 23, 2009 8:35 am    Post subject: Doing HTTP POST with the current SDK Reply with quote

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 :

Java:


public void MyFunction{
                HttpClient httpclient = new DefaultHttpClient();
                //Your URL
          HttpPost httppost = new HttpPost("http://www.myurl.com/script.php");

          try {
               List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        //Your DATA
               nameValuePairs.add(new BasicNameValuePair("id", "12345"));
               nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));

               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

               HttpResponse response;
               response=httpclient.execute(httppost);
          } catch (ClientProtocolException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
}




And here it is!
Back to top
View user's profile Send private message
wadael
Freshman
Freshman


Joined: 26 May 2009
Posts: 3
Location: FR

PostPosted: Tue May 26, 2009 8:45 pm    Post subject: Refactored Reply with quote

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.

Java:

package org.wadael.android.utils.net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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;
/**
 * A refactoring of the code provided by Moons on this page
 * http://www.anddev.org/doing_http_post_with_the_current_sdk-t5911.html
 *
 * Allows to send POST requests to a configurable server
 *
 * @author Moons, Wadael
 *
 */

public class HTTPPoster {

     public static HttpResponse doPost(String url, Map<String, String> kvPairs)
               throws ClientProtocolException, IOException {
          HttpClient httpclient = new DefaultHttpClient();
          HttpPost httppost = new HttpPost(url);

          if (kvPairs != null && kvPairs.isEmpty() == false) {
               List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                         kvPairs.size());
               String k, v;
               Iterator<String> itKeys = kvPairs.keySet().iterator();
               while (itKeys.hasNext()) {
                    k = itKeys.next();
                    v = kvPairs.get(k);
                    nameValuePairs.add(new BasicNameValuePair(k, v));
               }
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          }
          HttpResponse response;
          response = httpclient.execute(httppost);
          return response;
     }

}


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

Java:

public void onClick(View v) {
                    String url = SERVER.toASCIIString();
                    Map<String, String> kvPairs = new HashMap<String, String>();
                    
                    kvPairs.put("key1","value1");
                    kvPairs.put("key2","value2");
                    
                    try {
                         HttpResponse re = HTTPPoster.doPost(url, kvPairs);
                    } catch (ClientProtocolException e) {
                         e.printStackTrace();
                    } catch (IOException e) {
                         e.printStackTrace();
                                        // Do something
                    }
               }

Back to top
View user's profile Send private message Visit poster's website
wadael
Freshman
Freshman


Joined: 26 May 2009
Posts: 3
Location: FR

PostPosted: Tue May 26, 2009 9:43 pm    Post subject: Reply with quote

Now, if anybody knows how to retreive the content of the response, that would be good Very Happy
Back to top
View user's profile Send private message Visit poster's website
kali
Experienced Developer
Experienced Developer


Joined: 27 Jan 2009
Posts: 62

PostPosted: Tue Jun 02, 2009 6:34 am    Post subject: Reply with quote

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

pls!!!
Back to top
View user's profile Send private message
blade
Freshman
Freshman


Joined: 20 May 2009
Posts: 4

PostPosted: Sat Jun 06, 2009 8:56 am    Post subject: Reply with quote

@wadael

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

Anyway, it seem that code below would do the trick
Java:
temp1 = EntityUtils.toString(httpResponse.getEntity());


I used the code Moons supplied and added the code above and it works...
Back to top
View user's profile Send private message
wadael
Freshman
Freshman


Joined: 26 May 2009
Posts: 3
Location: FR

PostPosted: Sat Jun 06, 2009 9:45 pm    Post subject: HttpREsponse is richer Reply with quote

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 Sad


I've added this method to my class
Java:
ublic static String getPOSTResponse(String url, Map<String, String> kvPairs) throws ....


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
Back to top
View user's profile Send private message Visit poster's website
blade
Freshman
Freshman


Joined: 20 May 2009
Posts: 4

PostPosted: Mon Jun 08, 2009 12:03 pm    Post subject: Reply with quote

Variable httpResponse is actually of type HttpResponse...

You can get HTTP Status Code by using:
Java:
int statusCode = httpResponse.getStatusLine().getStatusCode();
Back to top
View user's profile Send private message
androiddev53
Freshman
Freshman


Joined: 19 May 2009
Posts: 4

PostPosted: Wed Jun 17, 2009 4:39 am    Post subject: hi Reply with quote

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
Back to top
View user's profile Send private message
vegolath
Once Poster
Once Poster


Joined: 29 Mar 2009
Posts: 1

PostPosted: Mon Aug 03, 2009 8:23 pm    Post subject: Reply with quote

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):


Java:

package com.vegolath.getandposttest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GetAndPost extends Activity {
   
     TextView tv;
     String text;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        tv = (TextView)findViewById(R.id.textveiw);
        text = "";
       
        postData();
    }
   
    public void postData(){  
     
              // Create a new HttpClient and Post Header  
              HttpClient httpclient = new DefaultHttpClient();  
              HttpPost httppost = new HttpPost("http://www.anddev.org/postresponse.php");  

          try {  
               // Add your data  
               List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
               nameValuePairs.add(new BasicNameValuePair("mydata", "Mek Mek"));    
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
     
               // Execute HTTP Post Request  
               HttpResponse response = httpclient.execute(httppost);
               
               InputStream is = response.getEntity().getContent();
               BufferedInputStream bis = new BufferedInputStream(is);
               ByteArrayBuffer baf = new ByteArrayBuffer(20);

                int current = 0;  
                while((current = bis.read()) != -1){  
                    baf.append((byte)current);  
                }  
                 
               /* Convert the Bytes read to a String. */  
               text = new String(baf.toByteArray());
               tv.setText(text);
     
          } catch (ClientProtocolException e) {  
               // TODO Auto-generated catch block  
          } catch (IOException e) {  
               // TODO Auto-generated catch block  
          }  
     }
}


Thanks!



get and post test success.png
 Description:
 Filesize:  6.85 KB
 Viewed:  5986 Time(s)

get and post test success.png


Back to top
View user's profile Send private message
sandis84
Experienced Developer
Experienced Developer


Joined: 07 Aug 2009
Posts: 78

PostPosted: Wed Aug 26, 2009 8:13 pm    Post subject: Reply with quote

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:

XML:
   <form action="/sign" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Post Greeting" /></div>
    </form>
Back to top
View user's profile Send private message
Ressor
Junior Developer
Junior Developer


Joined: 14 Oct 2009
Posts: 17
Location: Boston MA USA

PostPosted: Wed Oct 14, 2009 11:53 pm    Post subject: Reply with quote

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...
Back to top
View user's profile Send private message
Ressor
Junior Developer
Junior Developer


Joined: 14 Oct 2009
Posts: 17
Location: Boston MA USA

PostPosted: Thu Oct 15, 2009 12:32 am    Post subject: Reply with quote

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.
Back to top
View user's profile Send private message
burakkilic
Developer
Developer


Joined: 01 Oct 2009
Posts: 37

PostPosted: Fri Oct 16, 2009 4:10 pm    Post subject: Reply with quote

Thanks for this. Now I am trying to read an xml file into a string and Post that string. How can I achieve this?
Back to top
View user's profile Send private message
wander
Freshman
Freshman


Joined: 30 Jan 2010
Posts: 4

PostPosted: Sat Feb 06, 2010 8:19 pm    Post subject: Reply with quote

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 .
http://www.anddev.org/how_to_do_fetch_gmail_subject_list-t10862.html
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.