Brain Flush

October 17, 2008

Talking to Web Servers via HTTP in Android 1.0

Filed under: Mobile Devices, Software Development & Programming — Tags: , , , — Matthias @ 9:08 pm

If you have worked with Google Android prior to the 1.0 release, you probably have noticed that Google has upgraded the Apache HttpClient module in Android 1.0 from 3.x to a recent alpha release of version 4, which is a complete rewrite and brings with it a host of API changes. Unfortunately, the alpha version included in Android 1.0 is both terribly documented and lacking an important feature: supporting multipart requests using the multipart/form-data MIME type. Sending GET requests has changed significantly, too. Where you were formerly be able to add request parameters to a GetMethod object, you now will have to build a query string on your own and initialize an HttpGet object with it.

Here is how HTTP GET works in Android 1.0:

HttpClient httpClient = new DefaultHttpClient();

StringBuilder uriBuilder = new StringBuilder(SERVICE_ENDPOINT);
uriBuilder.append("?param0=" + param0);
uriBuilder.append("&param1=" + param1);
uriBuilder.append("&paramN=" + paramN);

HttpGet request = new HttpGet(uriBuilder.toString());
HttpResponse response = httpClient.execute(request);

int status = response.getStatusLine().getStatusCode();

// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
    response.getEntity().writeTo(ostream);
    Log.e("HTTP CLIENT", ostream.toString()));
} else {
    InputStream content = response.getEntity().getContent();
    // <consume response>
    content.close(); // this will also close the connection
}

Sending a multipart request first involves some environmental setup, since the required libraries are not bundled with Android 1.0. First, go to the Apache HttpClient download page and download the distribution called “Binary with dependencies”. In that package you’ll find two libraries: apache-mime4j-0.4.jar and httpmime-4.0-beta1.jar. Copy these files to e.g. the lib/ folder of your Android project and add them to the build path. You can now use a MultipartEntity to send multipart POSTs as such:

HttpClient httpClient = new DefaultHttpClient();

HttpPost request = new HttpPost(SERVICE_ENDPOINT);
MultipartEntity entity = new MultipartEntity();
entity.addPart("param0", new StringBody("value0"));
entity.addPart("param1", new StringBody(Double.toString(1.0)));
entity.addPart("paramN", new FileBody(new File("/bar/baz")));
request.setEntity(entity);

HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();

if (status != HttpStatus.SC_OK) {
    // see above   
} else {
    // see above
}

And that’s that. I assume Google has included this early build of HttpClient 4 in Android 1.0 so that they will remain API-stable for the years to come, without being stuck with a legacy HTTP component.

References:
http://groups.google.com/group/android-developers/browse_frm/thread/e4230ed22c196772
http://wiki.apache.org/HttpComponents/HttpCoreTutorial
http://hc.apache.org/httpcomponents-client/examples.html

About these ads

4 Comments »

  1. Hi

    There some problem in apache-mime4j-0.4.jar. StringTextBody missing class in org.apache.james.mime4j.message…

    But version 0.6 fix the problem

    Cheers.

    Comment by Konrad — August 30, 2010 @ 8:59 am

  2. Thanks for this post. Works like a charm.

    @Konrad It is not StringTextBody, but StringBody

    Comment by HRJ — December 1, 2010 @ 6:33 pm

  3. Hi to all,
    it is very useful for new android developers like me to learn most complex things.
    thanks for your good article.
    i have a requirement that, i want to post a newly recorded video file from my android device to a php server. i am able to send captured image files to the server as bitmap.but i am coming to video recording i am unable to send. can you explain me with some suitable example code how to capture a video and send that file to the php server using httppost method?

    thanks in advance
    sathish

    Comment by sathish — January 30, 2011 @ 6:53 pm

  4. Hi great post. In php how do you handle the file uploaded. Is it something along the lines of $_FILES["paramN"]?

    regards

    Comment by Andy — April 15, 2011 @ 6:18 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 37 other followers

%d bloggers like this: