Multipart Form Posting in Android

less than 1 minute read

I'm chugging away making a native Android app for the rather splendid @stringfellow.  It's been quite the eye-opener in terms of Android fragmentation, the joys of returning to Java after a (very) long hiatus and the intricacies of the platform as a whole.  I fully intend to write-up a few posts on what I've done (and hope for feedback on how things can be improved) but the following was an unexpected pitfall I think is worth talking about now.

Naturally the wealth of apps on Android and other mobile devices require some kind of network interface for consumption of data and communicating details back to servers.  Android - being built with Java - allows you to use the org.apache.http.client.HttpClient which is great until you want to send an image/file or anything else in a multi-part form.

The version of HttpClient in Android (2.2 - not developing against other versions yet) does not have support for multi-part forms.  You could write content as separate entities/directly to the stream but that can soon get messy.

To make things simpler, grab the HttpClient (4.1.3) jar from Apache, drop into your Android project build path and do the following in your request/response handler: