Android: Uploading files from the phone to a web server via HttpPost

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".

image

Now you're ready to CODE!

HttpClient httpClient;
HttpPost postRequest;
MultipartEntity reqEntity;
ResponseHandler responseHandler;
File file;
FileBody fileBody;

httpClient = new DefaultHttpClient();
postRequest = new HttpPost(targetUrl);
responseHandler = new BasicResponseHandler();

// Indicate that this information comes in parts (text and file)
reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

file = new File(filename);
fileBody = new FileBody(file, "images/jpeg");
reqEntity.addPart("fileupload", fileBody);

try {
// The rest of the mundane data
reqEntity.addPart("username", new StringBody("twig"));
reqEntity.addPart("password", new StringBody("haha_as_if!"));

// Prepare to ship it!
postRequest.setEntity(reqEntity);
httpClient.execute(postRequest, responseHandler);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}

The file mimetypes you can get from my post Android: Get file mime type from filename.

2clfkn
Now you ride like a BOSS!

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog