0 0 Votes

Android Programming: Send data via HTTP POST request

Tutorial by Progger99 | 20/11/2012 at 22:43

Android makes it easy for us to send data via HTTP POST to any website on the net. In this small tutorial, I will show you how to do it.

First, we need to get the necessary permissions. For that, we are writing the following line in the AndroidManifest.xml:

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

Without this line, our app can not access the internet later.

Next, we need two objects, a "client" and our "post". As a parameter, we pass the address of the script to our "post", to which the data should be sent later:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.example.com/script.php");

Before we start, we need a list containing our data, we would like to send. We take a "NameValuePair" list for that, so that we can define the names and the applicable related values.

List<NameValuePair> postlist = new ArrayList<NameValuePair>();
postlist.add(new BasicNameValuePair("key1", "value1"));
postlist.add(new BasicNameValuePair("key2", "value2"));

Next, we are using setEnitity() and UrlEncodedFormEntity to assign the list to our "post" in the right form.

try {
   post.setEntity(new UrlEncodedFormEntity(postlist));
} catch (UnsupportedEncodingException e) {
   throw new AssertionError("Encoding Error");
   // or
   Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}

Finally, we only need to run the POST request. We use the following line fot that:

try {
  HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
   throw new AssertionError("Client Protocol Error");
   // or
   Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
   throw new AssertionError("IO Error");
   // or
   Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}

We get back a HTTP response object that contains our response of the script. If we want, of course, we can also process and analyze this return object to get a feedback about the query.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.