How to POST an HTTP Request on Android

Table of contents:

How to POST an HTTP Request on Android
How to POST an HTTP Request on Android
Anonim

POSTing an HTTP request is an essential and basic step for all those Android applications that need to exploit internet resources. The only thing you will need to do is implement the function that will execute the request.

Steps

Execute HTTP POST Requests in Android Step 1
Execute HTTP POST Requests in Android Step 1

Step 1. Enter internet access permissions inside the manifest file by adding the following lines of code to the 'AndroidManifest

xml '. This way your application can use any internet connection active on the device.

Execute HTTP POST Requests in Android Step 2
Execute HTTP POST Requests in Android Step 2

Step 2. Create the 'HttpClient' and 'HttpPost' objects, they will be responsible for executing the 'POST' request

The 'address' object of type 'String' present in the code represents the destination on the web of your 'POST', and can be for example the address of a PHP page.

HttpClient client = new DefaultHttpClient ();

HttpPost post = new HttpPost (address);

Execute HTTP POST Requests in Android Step 3
Execute HTTP POST Requests in Android Step 3

Step 3. Set the data that will be sent from your 'POST'

You can do this by creating and enhancing a list of 'NameValuePair' as the entity of your 'HttpPost' object. Make sure you handle the 'UnsupportedEncodingException' which can be raised by the 'HttpPost.setEntity ()' method.

List pairs = new ArrayList ();

pairs.add (new BasicNameValuePair ("key1", "value1"));

pairs.add (new BasicNameValuePair ("key2", "value2"));

post.setEntity (new UrlEncodedFormEntity (pairs));

Step 4. Now all you have to do is perform your 'POST'

Your HTTP POST request will generate as a result an object of type 'HttpResponse' containing the data, which will then be extracted and interpreted ('parsing'). Make sure you handle the 'ClientProtocolException' and 'IOException' exceptions, which can be raised by the 'execute ()' method in case of an error.

HttpResponse response = client.execute (post);

Recommended: