pecet
pecet

Reputation: 125

Multi-part POST with file and string in HTTPClient 4.1

I need to create Multi-part POST request containing fields: update[image_title] = String update[image] = image-data itself. As you can see both are in associative array called "update". How could I do it with HTTPClient 4.1, because I found only examples for 3.x line of this library.

Thank you in advance.

Upvotes: 6

Views: 17193

Answers (2)

Niks
Niks

Reputation: 4832

Probably too late but might help someone. I had the exact same issue. Assuming that you have a file object which has necessary information about the image

HttpPost post = new HttpPost(YOUR_URL);
MultipartEntity entity = new MultipartEntity();
ByteArrayBody body = new ByteArrayBody(file.getData(), file.getName());     
String imageTitle = new StringBody(file.getName());

entity.addPart("imageTitle", imageTitle);
entity.addPart("image", body);
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
    try {
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Please note that MultiPartEntity is part of HttpMime module. So you need to put that jar in the lib directory or include as a (maven/gradle) dependency.

Upvotes: 13

mblinn
mblinn

Reputation: 3274

Yeah I've found it a real pain to find HTTP Client 4 examples, etc as well, since the almighty google almost always still points to HTTP 3.

At any rate, the last sample on this page - http://hc.apache.org/httpcomponents-client-ga/examples.html should be what you want.

Upvotes: 1

Related Questions