HTTPClient 4.1中的多部分POST请求:包含文件和字符串

6
我需要创建一个包含以下字段的多部分POST请求: update[image_title] = 字符串 update[image] = 图像数据本身。 如您所见,两者都在名为“update”的关联数组中。 我该如何使用HTTPClient 4.1实现它,因为我只找到了这个库3.x系列的示例。
提前致谢。
2个回答

13

也许已经太晚了,但可能会对某些人有所帮助。我曾遇到完全相同的问题。 假设您有一个文件对象,其中包含有关图像的必要信息。

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();
    }
请注意,MultiPartEntityHttpMime模块的一部分。因此,您需要将该jar文件放在lib目录中或将其包含为(maven/gradle)依赖项。

1

谢谢,但这并没有解决我的问题,我该如何将关联数组添加为请求参数?所包含的示例仅适用于“普通”参数。 - pecet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接