kerouac kerouac - 1 year ago 136
Java Question

Java equivalent of curl post request with image and text

I'm trying to write java code to do exactly what this command does:

curl -F "image=@image.jpg" -F "param1=some-value" -F "param2=some_value"

I'm currently trying something like this:

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost poster = new HttpPost("");
MultipartEntityBuilder mpEntityBuilder = MultipartEntityBuilder.create();
mpEntityBuilder.addPart("param1", new StringBody("some-value"));
mpEntityBuilder.addPart("param2", new StringBody("some-value"));
mpEntity.addPart("image", getImage("some-image"));
poster.setEntity(mpEntityBuilder .build());
HttpResponse response = httpClient.execute(poster);

here getImage(String) returns a ByteArrayBody. (I'm actually downloading an image from the web on the fly rather than reading from disk like the curl command, but I don't think this should make a difference)

I checked out this link it but it doesn't exactly address the case where you're sending both an image as well as text parameters:
Java Equivalent of curl query

What's strange is that I am using almost the same code to make an HTTP post to another API which works fine when I need to send an image alone without any textual parameters. (no stringbody)

But when I'm trying to send both an image(as a ByteArrayBody) and some text (as StringBody), I get a cryptic error message from the server that says something like:
'Could not initialize parameter object with mimeType: application/octet-stream'. It's probably a custom error message so I can't really find much information on this.

I tried using a few other constuctors for StringBody() since this one is deprecated, but it didn't help. Not sure what is the right constructor to use, but not sure if this would be causing a problem.

Edit: seems like someone's asked a very similar question before, but the solution does not work for me:
Android: upload file with filling out POST body together
I get an error message about
Failed parameter initialization with mimeType: application/octet-stream)

Answer Source

I don't see it documented but curl -F @ apparently trying to be helpful fills in Content-type for some extensions/suffixes, including image/jpeg for .jpg. HttpClient does not, and defaults everything to the MIME 'I don't know' type application/octet-stream which presumably caused your error. Use the 3-arg ctor that sets the content-type

new ByteArrayBody (data, ContentType.create("image/jpeg"), null)

or if you want to specify the filename attribute, which curl -F @ also does but web servers (unlike browsers) usually don't care about, supply a String in place of the null third argument.