Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 777
pecet Avatar asked Feb 21 '11 21:02

pecet


2 Answers

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.

like image 195
Niks Avatar answered Nov 14 '22 21:11

Niks


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.

like image 38
mblinn Avatar answered Nov 14 '22 22:11

mblinn