Doing HTTP POST with the current SDK

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

Postby prazannag » Fri Feb 26, 2010 7:01 am

I tried the code that you have posted earlier, but it seems answer as "false". Let me know how to fix this ?
Praz
User avatar
prazannag
Junior Developer
Junior Developer
 
Posts: 10
Joined: Fri Feb 05, 2010 7:34 pm
Location: India

Top

Postby himym » Fri Feb 26, 2010 5:03 pm

nice code thanks. but, is there any specific way to send that post via a specified port? i just use new HttpPost(http://mywebsite.com:1234/post.php) and I get a NoHttpResponseException, although I checked and got a positive answer if a connection can be established .
Can you give me some advice please!

Thanks
himym
Developer
Developer
 
Posts: 33
Joined: Sun Oct 18, 2009 9:50 am

Postby mistajase » Wed Mar 24, 2010 3:09 pm

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

Thank you for your patiences and help...



textview is not spelled correctly!

Line: tv = (TextView)findViewById(R.id.textveiw);
mistajase
Junior Developer
Junior Developer
 
Posts: 20
Joined: Thu Nov 26, 2009 4:28 am

Postby mistajase » Wed Mar 24, 2010 3:22 pm

prazannag wrote:I tried the code that you have posted earlier, but it seems answer as "false". Let me know how to fix this ?


add

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

to the manifest
mistajase
Junior Developer
Junior Developer
 
Posts: 20
Joined: Thu Nov 26, 2009 4:28 am

Postby Leviathan-Zero » Fri Mar 26, 2010 2:48 pm

Thanks a lot for the code you provided. :)
It really helped me out and was very easy to follow.
Thanks to Wadael, too, of course. ;)
Leviathan-Zero
Freshman
Freshman
 
Posts: 3
Joined: Fri Mar 26, 2010 2:39 pm

Re: Refactored

Postby pedroteixeira07 » Mon Apr 26, 2010 10:30 pm

wadael wrote: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. package org.wadael.android.utils.net;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  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. /**
  18.  * A refactoring of the code provided by Moons on this page
  19.  * doing_http_post_with_the_current_sdk-t5911.html
  20.  *
  21.  * Allows to send POST requests to a configurable server
  22.  *
  23.  * @author Moons, Wadael
  24.  *
  25.  */
  26. public class HTTPPoster {
  27.  
  28.         public static HttpResponse doPost(String url, Map<String, String> kvPairs)
  29.                         throws ClientProtocolException, IOException {
  30.                 HttpClient httpclient = new DefaultHttpClient();
  31.                 HttpPost httppost = new HttpPost(url);
  32.  
  33.                 if (kvPairs != null && kvPairs.isEmpty() == false) {
  34.                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
  35.                                         kvPairs.size());
  36.                         String k, v;
  37.                         Iterator<String> itKeys = kvPairs.keySet().iterator();
  38.                         while (itKeys.hasNext()) {
  39.                                 k = itKeys.next();
  40.                                 v = kvPairs.get(k);
  41.                                 nameValuePairs.add(new BasicNameValuePair(k, v));
  42.                         }
  43.                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  44.                 }
  45.                 HttpResponse response;
  46.                 response = httpclient.execute(httppost);
  47.                 return response;
  48.         }
  49.  
  50. }
  51.  
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. public void onClick(View v) {
  2.                                 String url = SERVER.toASCIIString();
  3.                                 Map<String, String> kvPairs = new HashMap<String, String>();
  4.                                
  5.                                 kvPairs.put("key1","value1");
  6.                                 kvPairs.put("key2","value2");
  7.                                
  8.                                 try {
  9.                                         HttpResponse re = HTTPPoster.doPost(url, kvPairs);
  10.                                 } catch (ClientProtocolException e) {
  11.                                         e.printStackTrace();
  12.                                 } catch (IOException e) {
  13.                                         e.printStackTrace();
  14.                                         // Do something
  15.                                 }
  16.                         }
  17.  
  18.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4

I get 2 errors:

The method toASCIIString is undefined for the type String

and

the local variable re is never used

Any suggestions ?
pedroteixeira07
Experienced Developer
Experienced Developer
 
Posts: 74
Joined: Sun Oct 18, 2009 6:06 pm
Location: Funchal

Top

Postby pedroteixeira07 » Tue Apr 27, 2010 9:42 am

Can someone help me with this issue from the example above please? I'm a newbie to Android and not the best with Java..

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. The local variable re is never read
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


I could really use having this POST method running for good.

How can I make this variable be read?
pedroteixeira07
Experienced Developer
Experienced Developer
 
Posts: 74
Joined: Sun Oct 18, 2009 6:06 pm
Location: Funchal

Postby pedroteixeira07 » Thu Apr 29, 2010 6:10 pm

This tutorial is driving me nuts!!!!! Sometimes it's working sometimes it's not.. I've been around this for two days... can ANYBODY help me please?

Here's the code:

A HTTPPoster Class on which I didn't change anything:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class HTTPPoster {
  3.  
  4.  
  5.  
  6.      public static HttpResponse doPost(String url, Map<String, String> kvPairs)
  7.  
  8.                throws ClientProtocolException, IOException {
  9.  
  10.           HttpClient httpclient = new DefaultHttpClient();
  11.  
  12.           HttpPost httppost = new HttpPost(url);
  13.  
  14.  
  15.  
  16.           if (kvPairs != null && kvPairs.isEmpty() == false) {
  17.  
  18.                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
  19.  
  20.                          kvPairs.size());
  21.  
  22.                String k, v;
  23.  
  24.                Iterator<String> itKeys = kvPairs.keySet().iterator();
  25.  
  26.                while (itKeys.hasNext()) {
  27.  
  28.                     k = itKeys.next();
  29.  
  30.                     v = kvPairs.get(k);
  31.  
  32.                     nameValuePairs.add(new BasicNameValuePair(k, v));
  33.  
  34.                }
  35.  
  36.                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  37.  
  38.           }
  39.  
  40.           HttpResponse response;
  41.  
  42.           response = httpclient.execute(httppost);
  43.  
  44.           return response;
  45.  
  46.      }
  47.  
  48.  
  49.  
  50. }
Parsed in 0.039 seconds, using GeSHi 1.0.8.4


And the method being used on the event of a Click on another class

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.      Button start = (Button) findViewById(R.id.startbutton);
  3.  
  4.        
  5.  
  6.       start.setOnClickListener(new View.OnClickListener() {    
  7.  
  8.           public void onClick(View view) {
  9.  
  10.               String url = "http://www.pedroteixeira.org/thennnow/UT1.php".toString();
  11.  
  12.               Map<String, String> kvPairs = new HashMap<String, String>();
  13.  
  14.  
  15.  
  16.               kvPairs.put("name","dfsgsdfgdsfg");
  17.  
  18.               kvPairs.put("email","dfbdfbdfbb");
  19.  
  20.                
  21.  
  22.               try {
  23.  
  24.                    HttpResponse re = HTTPPoster.doPost(url, kvPairs);
  25.  
  26.               } catch (ClientProtocolException e) {
  27.  
  28.                    e.printStackTrace();
  29.  
  30.               } catch (IOException e) {
  31.  
  32.                    e.printStackTrace();
  33.  
  34.                                   // Do something
  35.  
  36.               }
  37.  
  38.  
  39.  
  40.  
  41.  
  42.           }
  43.  
  44.       });}
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4


Please... what the hell am I doing wrong ?
Besides saying ''re'' is never read.. sometimes it passes the strings values sometimes it doesn't ..

My POST attributes to receive in the UT1.php file are ''name'' and ''email''.

How can I make this work? I'm kinda getting desperate !
pedroteixeira07
Experienced Developer
Experienced Developer
 
Posts: 74
Joined: Sun Oct 18, 2009 6:06 pm
Location: Funchal

Re: Doing HTTP POST with the current SDK

Postby garrettgjb » Wed Jun 23, 2010 8:41 pm

Could someone please post a solution that works. It looks like a lot of people can't get this working either. Thanks.
garrettgjb
Junior Developer
Junior Developer
 
Posts: 22
Joined: Mon Jun 14, 2010 3:55 pm

Re: Doing HTTP POST with the current SDK

Postby saki_kawa » Thu Jul 01, 2010 12:04 am

Hi guys!
I need a little help.. I've tested every code on this forum and other websites, sanitizing them or using as written, but I always return the same error: 417 Expectation Failed.. I don't know anything about status error different from 404, 500, and so on..
Someone with more experience have a clue??
Thanks you a lot! If someone will find an answer I'll work hard for this forum with some open code!! ;)
saki_kawa
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Jun 30, 2010 11:58 pm

Re: Doing HTTP POST with the current SDK

Postby garrettgjb » Sun Jul 04, 2010 6:12 am

Same, I can't get any of the code posted to work.
garrettgjb
Junior Developer
Junior Developer
 
Posts: 22
Joined: Mon Jun 14, 2010 3:55 pm

Re: Doing HTTP POST with the current SDK

Postby timwebuk » Thu Jul 08, 2010 11:29 am

Chances are the reason why your code isn't working is because you don't understand how to build an HTTP request. The code is fine, your headers and content probably isn't!

Using a network protocol analyser (such as Wireshark), or FireBug or Chrome's built in development tools, read the POST requests you make to websites then rebuild them (using the same headers) in Android.
VB6/C++/XML programmer - moving to the future, Android!
timwebuk
Freshman
Freshman
 
Posts: 8
Joined: Thu Jun 24, 2010 7:36 pm

Re: Doing HTTP POST with the current SDK

Postby flintman » Thu Sep 02, 2010 12:56 am

New to anddev.org. Hello all. I tried your script i added a little bit more to read a reply. Now using your data in php i have

Code: Select all
<?php>
echo "My id is ". $_POST['id']


When i display it on my android 2.1 phone it just says "My id is "

The web isn't getting the $_POST am i not getting the data correct using $_POST.

I even tried in php to use "print_r($_POST);" and all it displays array()

pre Thanks
flintman
Freshman
Freshman
 
Posts: 4
Joined: Thu Sep 02, 2010 12:19 am

Re: Doing HTTP POST with the current SDK

Postby tarunsez » Fri Sep 03, 2010 7:20 am

Thanks a lot for the code.. but the code provided above working perfectly as an independent application..
but when i try to call this from another activity, the application closes with an exception.


Please help me resolve this error at the earliest. I have a demo on monday of my applicaiton.
tarunsez
Freshman
Freshman
 
Posts: 2
Joined: Wed Sep 01, 2010 7:19 am

Re: Doing HTTP POST with the current SDK

Postby flintman » Fri Sep 03, 2010 5:58 pm

Code: Select all
public String POST(String action, String var1, String var2) {
      String answer = null;
      HttpParams params = new BasicHttpParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(url);
      
      try {
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
         // Your DATA
         nameValuePairs.add(new BasicNameValuePair("action", action));
         nameValuePairs.add(new BasicNameValuePair("var1", var1));
         nameValuePairs.add(new BasicNameValuePair("var2", var2));

         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity resEntity = response.getEntity();
         String ReTurned = EntityUtils.toString(resEntity);
         answer = ReTurned;
         Toast.makeText(this, answer, Toast.LENGTH_LONG).show();
      } catch (ClientProtocolException e) {
         Toast.makeText(this, "There was an issue Try again later", Toast.LENGTH_LONG).show();
      } catch (IOException e) {
         Toast.makeText(this, "There was an IO issue Try again later", Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
      
      return answer;
   }


I fixed my issue by adding in
Code: Select all
      HttpParams params = new BasicHttpParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


Also to the last poster the above i believe maybe what you are looking for.
flintman
Freshman
Freshman
 
Posts: 4
Joined: Thu Sep 02, 2010 12:19 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 13 guests