Execute HTTP POST Requests In Android


HTTP POST requests is essential to any Android apps that utilizes internet, follow the simple steps below to implement the functionality

  • Declare Internet permissions in the manifest by adding the following line to AndroidManifest.xml. This allows your application to use any Internet connections.
    <uses-permission android:name="android.permission.INTERNET" />
  • Create your HttpClient and HttpPost objects to execute the POST request. The address object is a String representing your POST's destination, such as a PHP page.

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(address);

  • Set your POST data. This is done by creating and setting a list of NameValuePairs as your HttpPost's entity. Be sure to catch the UnsupportedEncodingException thrown by HttpPost.setEntity().

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("key1", "value1"));
    pairs.add(new BasicNameValuePair("key2", "value2"));
    post.setEntity(new UrlEncodedFormEntity(pairs));

  • Execute the POST request. This returns an HttpResponse object, whose data can be extracted and parsed. Be sure to catch the ClientProtocolException and IOException thrown.

    HttpResponse response = client.execute(post);

Help Us Grow

If you like this post, please share it with your friends.

You are free to copy and redistribute this article in any medium or format, as long as you keep the links in the articles or provide a link back to this page.

Subscribe to our mailing list

You may also like...