java HTTPClient 4.1 中带有文件和字符串的多部分 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5071568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:16:56  来源:igfitidea点击:

Multi-part POST with file and string in HTTPClient 4.1

javaapache-httpclient-4.x

提问by pecet

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.

我需要创建一个包含域多部分POST请求: update[image_title] = String update[image] = image-data itself。如您所见,两者都在称为“更新”的关联数组中。我怎么能用 HTTPClient 4.1 做到这一点,因为我只找到了这个库的 3.x 行的例子。

Thank you in advance.

先感谢您。

回答by Niks

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 MultiPartEntityis part of HttpMimemodule. So you need to put that jar in the lib directory or include as a (maven/gradle) dependency.

请注意,这MultiPartEntityHttpMime模块的一部分。因此,您需要将该 jar 放在 lib 目录中或作为 (maven/gradle) 依赖项包含在内。

回答by mblinn

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.

是的,我发现找到 HTTP Client 4 示例等真的很痛苦,因为全能的谷歌几乎总是指向 HTTP 3。

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

无论如何,此页面上的最后一个示例 - http://hc.apache.org/httpcomponents-client-ga/examples.html应该是您想要的。