在HTTPClient 4.1中使用文件和字符串进行多部分POST [英] Multi-part POST with file and string in HTTPClient 4.1
问题描述
我需要创建包含字段的多部分POST请求:
update [image_title] = String
。
update [image] = image-data本身
正如你所看到的,两者都在称为更新的关联数组中。
我怎么能用HTTPClient 4.1来做,因为我只发现了这个库的3.x行的例子。
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.
提前谢谢。
推荐答案
可能为时已晚,但可能帮助他人。我有完全相同的问题。
假设你有一个文件对象,其中包含有关图像的必要信息
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();
}
请注意 MultiPartEntity
是 HttpMime
模块的一部分。因此,您需要将该jar放在lib目录中或包含为(maven / gradle)依赖项。
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.
这篇关于在HTTPClient 4.1中使用文件和字符串进行多部分POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!