Java equivalent of curl post request with image and text

 ̄綄美尐妖づ 提交于 2019-12-12 02:23:51

问题


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" http://example.com

I'm currently trying something like this:

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost poster = new HttpPost("http://example.com");
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)


回答1:


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.



来源:https://stackoverflow.com/questions/38679224/java-equivalent-of-curl-post-request-with-image-and-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!