Tuesday, October 8, 2013

Upload binary data

This is one of most interesting aspect. To handle this operation we need to add an external library to simplify the task. This is a drawback of using apache http client respect to the android native api. On the other side as we saw android native api doesn’t handle multipart request so we have to do everything from zero. Using this library we can simplify the process but we have as a consequence a bigger apk at the end. The library is open source and it is called httpmime-xxx.jar. You can download it here. Remember to add it to your project and has to be exported (see Order and Export in Eclipse). As example we create a multipart request containing some text data and an image. So we start creating always our DefaultHttpClient and HttpPost:
1HttpClient client = new DefaultHttpClient();
2HttpPost post = new HttpPost(url);
Now we have to create our post content, called Entity:
1MultipartEntity multiPart = new MultipartEntity();
and then add the single parts: two are text data and one is the binary data (the image we want to upload):
1multiPart.addPart("param1", new StringBody(param1));
2multiPart.addPart("param2", new StringBody(param2));
3multiPart.addPart("file", new ByteArrayBody(baos.toByteArray(), "logo.png"));
Notice at line 3 we create a part using a ByteArrayBody to contain the binary data. The we fill the post content with the data we created:
1post.setEntity(multiPart);
and then we simply send (or post) it to the server:
1client.execute(post);
Running the app we have:
android_http_apache_client_uploadServer sideandroid_http_apache_client_upload_server

No comments:

Post a Comment