Making a multipart/form-data POST request

77 views
Skip to first unread message

Jake Rockwell

unread,
Feb 2, 2014, 2:56:45 PM2/2/14
to google-http...@googlegroups.com
For an Android app I have to make a POST request with the "Content-Type" set to multipart/form-data, since I need to support the upload of files. However, I am unable to figure out how to do this. I think I need to use the classes MultipartContent and Part, but I do not know the correct way to use them.

I did manage to successfully use a regular "application/json" based POST as follows:

HttpContent content;

JSONObject defaultJsonObject = new JSONObject();
defaultJsonObject.put("firstname", "Testia");
defaultJsonObject.put("lastname", "Test");
defaultJsonObject.put("nickname", "Tes");
defaultJsonObject.put("dob", "1987-12-30");
defaultJsonObject.put("gender", "f");

content = ByteArrayContent.fromString("application/json", defaultJsonObject.toString());

HttpRequest request = getHttpRequestFactory()
.buildPostRequest(new GenericUrl( requestUrl ), content);
request.setParser( new JacksonFactory().createJsonObjectParser() );
HttpResponse response = request.execute();

How should I adapt above code to send the request as a multipart/form-data request? Furthermore, how should I extend the request to allow the sending of files? 

Thank you in advance!

Reply all
Reply to author
Forward
0 new messages