| Author |
Message |
Moons Junior Developer

Joined: 13 Feb 2009 Posts: 23
|
Posted: Thu Apr 23, 2009 8:35 am Post subject: Doing HTTP POST with the current SDK |
|
|
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 |
|
 |
|
|
 |
wadael Freshman

Joined: 26 May 2009 Posts: 3 Location: FR
|
Posted: Tue May 26, 2009 8:45 pm Post subject: Refactored |
|
|
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 |
|
 |
wadael Freshman

Joined: 26 May 2009 Posts: 3 Location: FR
|
Posted: Tue May 26, 2009 9:43 pm Post subject: |
|
|
Now, if anybody knows how to retreive the content of the response, that would be good
|
|
| Back to top |
|
 |
kali Experienced Developer

Joined: 27 Jan 2009 Posts: 62
|
Posted: Tue Jun 02, 2009 6:34 am Post subject: |
|
|
hai moons,
would you teach me how whole code is working with complete samplecode.
pls!!!
|
|
| Back to top |
|
 |
blade Freshman

Joined: 20 May 2009 Posts: 4
|
Posted: Sat Jun 06, 2009 8:56 am Post subject: |
|
|
@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 |
|
 |
wadael Freshman

Joined: 26 May 2009 Posts: 3 Location: FR
|
|
| Back to top |
|
 |
|
|
 |
blade Freshman

Joined: 20 May 2009 Posts: 4
|
Posted: Mon Jun 08, 2009 12:03 pm Post subject: |
|
|
Variable httpResponse is actually of type HttpResponse...
You can get HTTP Status Code by using:
| Java: | int statusCode = httpResponse.getStatusLine().getStatusCode(); |
|
|
| Back to top |
|
 |
androiddev53 Freshman

Joined: 19 May 2009 Posts: 4
|
Posted: Wed Jun 17, 2009 4:39 am Post subject: hi |
|
|
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 |
|
 |
vegolath Once Poster

Joined: 29 Mar 2009 Posts: 1
|
Posted: Mon Aug 03, 2009 8:23 pm Post subject: |
|
|
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!
| Description: |
|
| Filesize: |
6.85 KB |
| Viewed: |
5986 Time(s) |

|
|
|
| Back to top |
|
 |
sandis84 Experienced Developer

Joined: 07 Aug 2009 Posts: 78
|
Posted: Wed Aug 26, 2009 8:13 pm Post subject: |
|
|
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 |
|
 |
Ressor Junior Developer

Joined: 14 Oct 2009 Posts: 17 Location: Boston MA USA
|
Posted: Wed Oct 14, 2009 11:53 pm Post subject: |
|
|
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 |
|
 |
Ressor Junior Developer

Joined: 14 Oct 2009 Posts: 17 Location: Boston MA USA
|
Posted: Thu Oct 15, 2009 12:32 am Post subject: |
|
|
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 |
|
 |
burakkilic Developer

Joined: 01 Oct 2009 Posts: 37
|
Posted: Fri Oct 16, 2009 4:10 pm Post subject: |
|
|
| 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 |
|
 |
wander Freshman

Joined: 30 Jan 2010 Posts: 4
|
|
| Back to top |
|
 |
|