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:
1 | HttpClient client = new DefaultHttpClient(); |
2 | HttpPost post = new HttpPost(url); |
Now we have to create our post content, called Entity:
1 | MultipartEntity 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):
1 | multiPart.addPart( "param1" , new StringBody(param1)); |
2 | multiPart.addPart( "param2" , new StringBody(param2)); |
3 | multiPart.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:
1 | post.setEntity(multiPart); |
and then we simply send (or post) it to the server:
Running the app we have:
| Server side |
No comments:
Post a Comment