Using the Http Client for Http Post Requests

Making an HTTP POST call is very similar to making an HTTP GET call (see Listing 8-3).

Listing 8-3. Making an HTTP POST Request with the HttpClient import java.util.ArrayList; import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

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;

public class TestHttpPost {

public String executeHttpPost() throws Exception { BufferedReader in = null; try {

HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(


List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("one", "valueGoesHere")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters);

request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent()));

StringBuffer sb = new StringBuffer(""); String line = "";

String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL);

String result = sb.toString(); return result;

in.close(); } catch (IOException e) { e.printStackTrace();

To make an HTTP POST call with the HttpClient, you have to call the execute method of the HttpClient with an instance of HttpPost. When making HTTP POST calls, you generally pass URL-encoded name/value form parameters as part of the HTTP request. To do this with the HttpClient, you have to create a list that contains instances of NameValuePair objects and then wrap that list with a UrlEncodedFormEntity object. The NameValuePair wraps a name/value combination and the UrlEncodedFormEntity class knows how to encode a list of NameValuePair objects suitable for HTTP calls (generally POST calls). After you create a UrlEncodedFormEntity, you can set the entity type of the HttpPost to the UrlEncodedFormEntity and then execute the request.

In Listing 8-3, we create an HttpClient and then instantiate the HttpPost with the URL of the HTTP endpoint. Next we create a list of NameValuePair objects and populate that with a single name/value parameter. We set the name of the parameter to one and the value of the parameter to valueGoesHere. We then create a UrlEncodedFormEntity instance, passing the list of NameValuePair objects to its constructor. Finally, we call the setEntity() method of the POST request and then execute the request using the HttpClient instance.

HTTP POST is actually much more powerful than this. With an HTTP POST, we can pass simple name/value parameters, as shown in Listing 8-3, as well as complex parameters such as files. HTTP POST supports another request-body format known as a "multipart POST." With this type of POST, you can send name/value parameters as before, along with arbitrary files. Unfortunately, the version of HttpClient shipped with Android does not directly support multipart POST. To do multipart POST calls, you need to get three additional Apache open source projects: Apache Commons IO, Mime4j, and HttpMime. You can download these projects from the following web sites:

• Commons IO:

• Mime4j:

• HttpMime:

Alternatively, you can visit this site to download all of the required .jar files to do multipart POST with Android:

Listing 8-4 demonstrates a multipart POST using Android.

Listing 8-4. Making a Multipart POST Call import; import;

import; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient;


public class TestMultipartPost extends Activity {

public void executeMultipartPost()throws Exception {

InputStream is = this.getAssets().open("data.xml"); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("");

byte[] data = IOUtils.toByteArray(is);

InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");

StringBody sb1 = new StringBody("someTextGoesHere"); StringBody sb2 = new StringBody("someTextGoesHere too");

MultipartEntity multipartContent = new MultipartEntity(); multipartContent.addPart("uploadedFile", isb); multipartContent.addPart("one", sbl); multipartContent.addPart("two", sb2);

postRequest.setEntity(multipartContent); HttpResponse res =httpClient.execute(postRequest); res.getEntity().getContent().close();

throw e;

Note The multipart example uses several .jar files that are not included as part of the Android runtime. To ensure that the .jar files will be packaged as part of your .apk file, you need to add them as external .jar files in Eclipse: right-click your project in Eclipse, select Properties, choose Java Class Path, select the Libraries tab, and then select Add External JARs.

Following these steps will make the .jar files available during compile time as well as runtime.

To execute a multipart POST, you need to create an HttpPost and call its setEntity() method with a MultipartEntity instance (rather than the UrlEncodedFormEntity we created for the name/ value parameter form post). MultipartEntity represents the body of a multipart POST request. As shown, you create an instance of a MultipartEntity and then call the addPart() method with each part. Listing 8-4 adds three parts to the request: two string parts and an XML file.

Finally, if you are building an application that requires you to pass a multipart POST to a web resource, you'll likely have to debug the solution using a dummy implementation of the service on your local workstation. You can access the local machine by using localhost or IP address With Android applications, however, you will not be able to use localhost (or because the emulator will have its own localhost. To refer to your development workstation from the application running in the emulator, you'll have to use your workstation's IP address. On a Windows XP machine, you can obtain your IP address by running the IPConfig DOS command. You would need to modify Listing 8-4 by substituting the IP address with the IP address of your workstation.

0 0

Post a comment