Alright, I'm getting sleepy so this post is straight down to business.
The early Android core libraries didn't come with very much in terms of HTTP and net socket support. The majority of the time they just said "use Apache's library, they're better".
Android has caught up, but if you want to keep existing devices happy, you'll still need the Apache libraries.
- Under HttpClient 4.1.2 (GA), download 4.1.2.zip.
- Create a folder in your project called "lib".
- Open up the zip archive and look for "httpcomponents-client-4.1.2-bin-2.zip\httpcomponents-client-4.1.2\lib\httpmime-4.1.2.jar"
- Extract it into the new lib folder.
In Eclipse:
- Refresh your project
- Right click your project
- Select "Properties"
- Go to "Java Build Path > Libraries > Add Jars"
- Select "httpmime-4.1.2.jar".
Now you're ready to CODE!
01.
HttpClient httpClient;
02.
HttpPost postRequest;
03.
MultipartEntity reqEntity;
04.
ResponseHandler<string> responseHandler;
05.
File file;
06.
FileBody fileBody;
07.
08.
httpClient =
new
DefaultHttpClient();
09.
postRequest =
new
HttpPost(targetUrl);
10.
responseHandler =
new
BasicResponseHandler();
11.
12.
// Indicate that this information comes in parts (text and file)
13.
reqEntity =
new
MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
14.
15.
file =
new
File(filename);
16.
fileBody =
new
FileBody(file,
"images/jpeg"
);
17.
reqEntity.addPart(
"fileupload"
, fileBody);
18.
19.
try
{
20.
// The rest of the mundane data
21.
reqEntity.addPart(
"username"
,
new
StringBody(
"twig"
));
22.
reqEntity.addPart(
"password"
,
new
StringBody(
"haha_as_if!"
));
23.
24.
// Prepare to ship it!
25.
postRequest.setEntity(reqEntity);
26.
httpClient.execute(postRequest, responseHandler);
27.
}
28.
catch
(UnsupportedEncodingException e) {
29.
e.printStackTrace();
30.
}
31.
catch
(ClientProtocolException e) {
32.
e.printStackTrace();
33.
}
34.
catch
(IOException e) {
35.
e.printStackTrace();
36.
} </string>
The file mimetypes you can get from my post Android: Get file mime type from filename.