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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With