I need to send multipart/form-data content to a web server and receive and parse multipart/form-data in the response. I have read multiple posts about how multipart content can be sent to server and parsed on the server. For ex: see here. But I found no post online that talks about sending a binary file and some other key-value pairs from server to client (a pojo or android activity in my case). Any help will be much appreciated.
1 Answers
I waited for a while and found no answers to my question. I have found a solution myself. Although I dont think its the most efficient, it removes the hurdle and lets me proceed. Here is the solution:
On the sender's side (server or client): Use org.apache.commons.codec.binary.Base64 to encodeToString(byte[] fileRepresentedAsBytes) and send HTTP Content-Type=text/plain.
On the receiver side (server or client): Use org.apache.commons.codec.binary.Base64.decode method to get the bytes[] back and create your file from it.
Here is the code for the http servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
File file = new File(<your-file-here>);
Base64 b = new Base64();
String fileStr = b.encodeToString(IOUtils.toByteArray(new FileInputStream(file)));
String queryString = "file=" + fileStr + "&foo=bar";
resp.setHeader("Content-Type", "text/plain");
resp.getWriter().print(queryString);
resp.getWriter().flush();
resp.getWriter().close();
}
On the client side, just use a query string parser from apache http utils and use Base64.decode. This will enable you to pass file and other plain text params between client and server. Remember that the client in my case is a POJO object and not a browser. Thats why I say it doesn't matter if you want to send a file from client to server or from server to client.
Ill be happy to learn alternate, more efficient methods if someone can post them here.

- 21
- 3
-
isn't there things like Google's ProtoBuf for sending binary data? Is that what you're looking for? As in you can send XML, JSON, HTML, or Binary formatted data. – Dandre Allison Sep 09 '12 at 22:18