HTTPClient 4.1 中带有文件和字符串的多部分 POST [英] Multi-part POST with file and string in HTTPClient 4.1

查看:24
本文介绍了HTTPClient 4.1 中带有文件和字符串的多部分 POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建包含字段的多部分 POST 请求:update[image_title] = 字符串更新[图像] = 图像数据本身.如您所见,两者都在称为更新"的关联数组中.我怎么能用 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();
    }

请注意 MultiPartEntityHttpMime 模块的一部分.因此,您需要将该 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆