HTTPclient使用multipartformentityEntity怎么上传文件

使用 HttpClient 4 进行文件上传 - 技术翻译 - 开源中国社区
使用 HttpClient 4 进行文件上传
【已翻译100%】
英文原文:
推荐于 3年前 (共 3 段, 翻译完成于 05-27)
参与翻译&(1人)&:
本教程我们将描述如何使用HttpClient 4进行一次多文件上传操作.
我们将使用&&作为测试服务器,因为它是面向公众的,并且接受大多数类型的内容.
如果你想要深入学习并了解你可以使用&HttpClient 做到的其它很棒的事情&– 那就去看看&.
2. 使用&AddPart&方法
让我们开始研究研究&MultipartEntityBuilder&对象,来向一个Http实体添加成分,它在稍后将会被通过一个POST操作上传.
这是向一个HttpEntity添加成分来表示表单的一般方法.
示例 2.1. - 使用两个文本成分和一个文件上传一个表单
File&file&=&new&File(textFileName,&ContentType.DEFAULT_BINARY);
HttpPost&post&=&new&HttpPost("");
FileBody&fileBody&=&new&FileBody(file);
StringBody&stringBody1&=&new&StringBody("Message&1",&ContentType.MULTIPART_FORM_DATA);
StringBody&stringBody2&=&new&StringBody("Message&2",&ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder&builder&=&MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile",&fileBody);
builder.addPart("text1",&stringBody1);
builder.addPart("text2",&stringBody2);
HttpEntity&entity&=&builder.build();
post.setEntity(entity);
HttpResponse&response&=&client.execute(post);
请注意我们也通过制定将会被服务器使用到的ContentType值来实例化File对象.
同样还请注意&addPart&方法有两个参数,作用就像是表单的键值对&. 除非服务器端实际需要这些值并使用了这些参数名称,它们就是有干系的,否则它们就会被简单的忽略掉.
&翻译得不错哦!
3. 使用&addBinaryBody&和&addTextBody&方法
创建一个multipart实体更直接的方式就是使用&addBinaryBody&和&AddTextBody& 方法. 这些方法服务于上传文本,文件,字符数组和&InputStream&对象. 我们用了一个简单的例子来描述如何使用它们 .
示例 3.1. - 上传一个文本和一个文本文件部分
HttpPost&post&=&new&HttpPost("");
File&file&=&new&File(textFileName);
String&message&=&"This&is&a&multipart&post";
MultipartEntityBuilder&builder&=&MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile",&file,&ContentType.DEFAULT_BINARY,&textFileName);
builder.addTextBody("text",&message,&ContentType.DEFAULT_BINARY);
HttpEntity&entity&=&builder.build();
post.setEntity(entity);
HttpResponse&response&=&client.execute(post);
注意这里不需要&FileBody&和&StringBody&对象
同样重要的是,大多数服务器不会检查文本体的&ContentType&, 因此&addTextBody&方法可能会忽略掉&ContentType&值 .
&addBinaryBody 的&API 接受一个&ContentType&- 但是它也有可能从一个二进制体来创建实体,而对应名称的表单参数持有了这个文件. 如前面小节所述,如果ContentType值没有被指定,一些服务器将不会识别这个文件.
&翻译得不错哦!
接下来,我们将一个zip文件作为一个&InputStream 添加进来,&而图片文件将会被作为File对象被添加进来:
示例 3.2. - 上传一个Zip文件,一个图片文件和一个文本块
HttpPost&post&=&new&HttpPost("");
InputStream&inputStream&=&new&FileInputStream(zipFileName);
File&file&=&new&File(imageFileName);
String&message&=&"This&is&a&multipart&post";
MultipartEntityBuilder&builder&=&MultipartEntityBuilder.create();&&&&&&&&&
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody
&&("upfile",&file,&ContentType.DEFAULT_BINARY,&imageFileName);
builder.addBinaryBody
&&("upstream",&inputStream,&ContentType.create("application/zip"),&zipFileName);
builder.addTextBody("text",&message,&ContentType.TEXT_PLAIN);
HttpEntity&entity&=&builder.build();
post.setEntity(entity);
HttpResponse&response&=&client.execute(post);
请注意ContentType值可以被动态创建,正如上面这个针对zip文件的示例中所示&.
最后,不是所有的服务器都接受&InputStream&部分. 我们在代码的第一行实体化的服务器可以接受&.
让我们现在来看看另外一个示例,&addBinaryBody直接用于一个位数组&:
示例 3.3. - 上传一个位数组和文本
HttpPost&post&=&new&HttpPost("");
String&message&=&"This&is&a&multipart&post";
byte[]&bytes&=&"binary&code".getBytes();&
MultipartEntityBuilder&builder&=&MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile",&bytes,&ContentType.DEFAULT_BINARY,&textFileName);
builder.addTextBody("text",&message,&ContentType.TEXT_PLAIN);
HttpEntity&entity&=&builder.build();
post.setEntity(entity);
HttpResponse&response&=&client.execute(post);
留意ContentType&- 它现在被指定为二进制数据.
本文呈现了&MultipartEntityBuilder 作为一个灵活的对象提供了创建一个&multipart 表单多种API.
示例同样也展示了如何使用HttpClient上传一个类似于表单实体的HttpEntity&.
这些示例的所有实现和代码块在&&中可以找到 – 这是一个基于Eclipse的项目, 因此可以很容易的导入并运行.
&翻译得不错哦!
我们的翻译工作遵照 ,如果我们的工作有侵犯到您的权益,请及时联系我们
暂无网友评论[摘要:媒介
正在开辟傍边,我们经常须要完成文件上传,比拟常睹的便是上传,比方点窜个头像甚么的。然则那个功效正在战iOS中皆出有默许的完成类,对Android我们可使用Apach]
在开发当中,我们常常需要实现文件上传,比较常见的就是图片上传,比如修改个头像什么的。但是这个功能在Android和iOS中都没有默认的实现类,对于Android我们可以使用Apache提供的HttpClient.jar来实现这个功能,其中依赖的类就是Apache的httpmime.jar中的MultipartEntity这个类。我就是要实现一个文件上传功能,但是我还得下载一个jar包,而这个jar包几十KB,这尼玛仿佛并非人间!今天我们就来自己实现文件上传功能,并且弄懂它们的原理。
在上一篇HTTP
POST请求报文格式分析与实现文件上传中我们介绍了HTTP POST报文格式,如果有对POST报文格式不了解的同学可以先阅读这篇文章。
自定义实现MultipartEntity
我们知道,使用协议传输数据无非就是要遵循某个协议,我们在开发时基本上都是使用HTTP协议。HTTP协议说白了就是基于TCP的一套网络请求协议,你根据该协议规定的格式传输数据,然后返回给你数据。你的协议参数要是传递错了,那么服务器只能给你返回错误。
这跟间谍之间对暗号有点相似,他们有一个规定的暗号,双方见面,A说:&天王盖地虎,B对:
宝塔镇河妖。对上了,说事;对不上,弄死这B。HTTP也是这样的,在HTTP请求时添加header和参数,服务器根据参数进行解析。形如 :&
POST /api/feed/ HTTP/1.1
这里是header数据
只要根据格式来向服务器发送请求就万事大吉了!下面我们就来看MultipartEntity的实现:
public class MultipartEntity implements HttpEntity {
private final static char[] MULTIPART_CHARS = &-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&
.toCharArray();
private final String NEW_LINE_STR = &\r\n&;
private final String CONTENT_TYPE = &Content-Type: &;
private final String CONTENT_DISPOSITION = &Content-Disposition: &;
* 文本参数和字符集
private final String TYPE_TEXT_CHARSET = &text/ charset=UTF-8&;
* 字节流参数
private final String TYPE_OCTET_STREAM = &application/octet-stream&;
private final byte[] BINARY_ENCODING = &Content-Transfer-Encoding: binary\r\n\r\n&.getBytes();
* 文本参数
private final byte[] BIT_ENCODING = &Content-Transfer-Encoding: 8bit\r\n\r\n&.getBytes();
private String mBoundary =
ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream();
public MultipartEntity() {
this.mBoundary = generateBoundary();
* 生成分隔符
private final String generateBoundary() {
final StringBuffer buf = new StringBuffer();
final Random rand = new Random();
for (int i = 0; i & 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
return buf.toString();
* 参数开头的分隔符
* @throws IOException
private void writeFirstBoundary() throws IOException {
mOutputStream.write((&--& + mBoundary + &\r\n&).getBytes());
* 添加文本参数
* @param key
* @param value
public void addStringPart(final String paramName, final String value) {
writeToOutputStream(paramName, value.getBytes(), TYPE_TEXT_CHARSET, BIT_ENCODING, &&);
* 将数据写入到输出流中
* @param key
* @param rawData
* @param type
* @param encodingBytes
* @param fileName
private void writeToOutputStream(String paramName, byte[] rawData, String type,
byte[] encodingBytes,
String fileName) {
writeFirstBoundary();
mOutputStream.write((CONTENT_TYPE + type + NEW_LINE_STR).getBytes());
mOutputStream
.write(getContentDispositionBytes(paramName, fileName));
mOutputStream.write(encodingBytes);
mOutputStream.write(rawData);
mOutputStream.write(NEW_LINE_STR.getBytes());
} catch (final IOException e) {
e.printStackTrace();
* 添加二进制参数, 例如Bitmap的字节流参数
* @param key
* @param rawData
public void addBinaryPart(String paramName, final byte[] rawData) {
writeToOutputStream(paramName, rawData, TYPE_OCTET_STREAM, BINARY_ENCODING, &no-file&);
* 添加文件参数,可以实现文件上传功能
* @param key
* @param file
public void addFilePart(final String key, final File file) {
InputStream fin =
fin = new FileInputStream(file);
writeFirstBoundary();
final String type = CONTENT_TYPE + TYPE_OCTET_STREAM + NEW_LINE_STR;
mOutputStream.write(getContentDispositionBytes(key, file.getName()));
mOutputStream.write(type.getBytes());
mOutputStream.write(BINARY_ENCODING);
final byte[] tmp = new byte[4096];
int len = 0;
while ((len = fin.read(tmp)) != -1) {
mOutputStream.write(tmp, 0, len);
mOutputStream.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeSilently(fin);
private void closeSilently(Closeable closeable) {
if (closeable != null) {
closeable.close();
} catch (final IOException e) {
e.printStackTrace();
private byte[] getContentDispositionBytes(String paramName, String fileName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(CONTENT_DISPOSITION + &form- name=\&& + paramName + &\&&);
// 文本参数没有filename参数,设置为空即可
if (!TextUtils.isEmpty(fileName)) {
stringBuilder.append(&; filename=\&&
+ fileName + &\&&);
return stringBuilder.append(NEW_LINE_STR).toString().getBytes();
public long getContentLength() {
return mOutputStream.toByteArray().
public Header getContentType() {
return new BasicHeader(&Content-Type&, &multipart/form- boundary=& + mBoundary);
public boolean isChunked() {
public boolean isRepeatable() {
public boolean isStreaming() {
public void writeTo(final OutputStream outstream) throws IOException {
// 参数最末尾的结束符
final String endString = &--& + mBoundary + &--\r\n&;
// 写入结束符
mOutputStream.write(endString.getBytes());
outstream.write(mOutputStream.toByteArray());
public Header getContentEncoding() {
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
&Streaming entity does not implement #consumeContent()&);
public InputStream getContent() {
return new ByteArrayInputStream(mOutputStream.toByteArray());
用户可以通过addStringPart、addBinaryPart、addFilePart来添加参数,分别表示添加参数、添加二进制参数、添加文件参数。在MultipartEntity中有一个ByteArrayOutputStream对象,先将这些参数写到这个输出流中,当执行网络请求时,会执行
writeTo(final OutputStream outstream)
方法将所有参数的字节流数据写入到与服务器建立的TCP连接的输出流中,这样就将我们的参数传递给服务器了。当然在此之前,我们需要按照格式来向ByteArrayOutputStream对象中写数据。
例如我要向服务器发送一个文本、一张bitmap图片、一个文件,即这个请求有三个参数。代码如下
MultipartEntity multipartEntity = new MultipartEntity();
// 文本参数
multipartEntity.addStringPart(&type&, &我的文本参数&);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.thumb);
// 二进制参数
multipartEntity.addBinaryPart(&images&, bitmapToBytes(bmp));
// 文件参数
multipartEntity.addFilePart(&images&, new File(&storage/emulated/0/test.jpg&));
// POST请求
HttpPost post = new HttpPost(&url&) ;
// 将multipartEntity设置给post
post.setEntity(multipartEntity);
// 使用http client来执行请求
HttpClient httpClient = new DefaultHttpClient() ;
httpClient.execute(post) ;
MultipartEntity的输出格式会成为如下的格式 :&
POST /api/feed/ HTTP/1.1
Content-Type: multipart/form- boundary=o3Fhj53z-oKToduAElfBaNU4pZhp4-
User-Agent: Dalvik/1.6.0 (; U; Android 4.4.4; M040 Build/KTU84P)
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 168518
--o3Fhj53z-oKToduAElfBaNU4pZhp4-
Content-Type: text/ charset=UTF-8
Content-Disposition: form- name=&type&
Content-Transfer-Encoding: 8bit
This my type
--o3Fhj53z-oKToduAElfBaNU4pZhp4-
Content-Type: application/octet-stream
Content-Disposition: form- name=&images&; filename=&no-file&
Content-Transfer-Encoding: binary
这里是bitmap的二进制数据
--o3Fhj53z-oKToduAElfBaNU4pZhp4-
Content-Type: application/octet-stream
Content-Disposition: form- name=&file&; filename=&storage/emulated/0/test.jpg&
Content-Transfer-Encoding: binary
这里是图片文件的二进制数据
--o3Fhj53z-oKToduAElfBaNU4pZhp4---
看到很熟悉吧,这就是我们在文章开头时提到的POST报文格式。没错!HttpEntity就是负责将参数构造成HTTP的报文格式,文本参数该是什么格式、文件该是什么格式,什么类型,这些格式都是固定的。构造完之后,在执行请求时会将http请求的输出流通过writeTo(OutputStream) 函数传递进来,然后将这些参数数据全部输出到http输出流中即可。
明白了这些道理,看看代码也就应该明白了吧。
Volley中实现文件上传
Volley是官方推出的网络请求库,这个库很精简、优秀,但是他们也没有默认添加文件上传功能的支持。我们今天就来自定义一个Request实现文件上传功能,还是需要借助上面的MultipartEntity类,下面看代码:
* @author mrsimple
public class MultipartRequest extends Request&String& {
MultipartEntity mMultiPartEntity = new MultipartEntity();
Map&String, String& mHeaders = new HashMap&String, String&();
private final Listener&String& mL
* Creates a new request with the given url.
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
public MultipartRequest(String url, Listener&String& listener) {
this(url, listener, null);
* Creates a new POST request.
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
public MultipartRequest(String url, Listener&String& listener, ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener =
public MultipartEntity getMultiPartEntity() {
return mMultiPartE
public String getBodyContentType() {
return mMultiPartEntity.getContentType().getValue();
public void addHeader(String key, String value) {
mHeaders.put(key, value);
public Map&String, String& getHeaders() throws AuthFailureError {
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// multipart body
mMultiPartEntity.writeTo(bos);
} catch (IOException e) {
Log.e(&&, &IOException writing to ByteArrayOutputStream&);
return bos.toByteArray();
protected Response&String& parseResponse(NetworkResponse response) {
String parsed = &&;
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
protected void deliverResponse(String response) {
if (mListener != null) {
mListener.onResponse(response);
使用示例代码:&
RequestQueue queue = Volley.newRequestQueue(this);
MultipartRequest multipartRequest = new MultipartRequest(
&&, new Listener&String&() {
public void onResponse(String response) {
Log.e(&&, &### response : & + response);
// 添加header
multipartRequest.addHeader(&header-name&, &value&);
// 通过MultipartEntity来设置参数
MultipartEntity multi = multipartRequest.getMultiPartEntity();
// 文本参数
multi.addStringPart(&location&, &模拟的地理位置&);
multi.addStringPart(&type&, &0&);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.thumb);
// 直接从上传Bitmap
multi.addBinaryPart(&images&, bitmapToBytes(bitmap));
// 上传文件
multi.addFilePart(&imgfile&, new File(&storage/emulated/0/test.jpg&));
// 将请求添加到队列中
queue.add(multipartRequest);
这是我post到我的应用的截图 :&
& & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & &&
注意,MultipartRequest并不适合大文件上传,如果是大文件上传则需要分段上传,否则会出现OOM。最后给出&github链接。
jQuery插件AjaxFileUpload文件上传实现多文件上传功能
4.3.2: Struts2文件上传---实现文件上传的Action
文件上传实现(java实现)
asp.net+C#实现文件上传实现代码
Servlet实现单个文件上传实现
【ASP.NET】Plupload多格式多文件上传实现
php多文件上传实现代码
struts多文件上传实现
php文件上传实现进度条使用HttpClient4实现API测试实战(2)——多附件上传 - 常想一二 - ITeye技术网站
博客分类:
0、特别说明
1、声明:如需转载,请注明来自 /;
2、阅读本文前建议先阅读下面博客:
1、引言
API测试过程中,有些API接口可能需要上传附件,而且是多个附件,本文主要是解决API测试过程中的多附件上传问题。
当然,你也可以将本文当作使用HttpClient模拟HTTP实现多附件上传的文章来阅读。
2、更新测试项目
2.1 添加项目依赖
httpmime-4.2.1.jar
2.2 修改HttpClient帮助类HttpClientUtil
添加下面方法
public static String doPostUpload(String url, List&BasicNameValuePair& datas, List&String& files) {
// 组装提交信息
MultipartEntity reqEntity = new MultipartEntity();
for(BasicNameValuePair data : datas) {
reqEntity.addPart(data.getName(), new StringBody(data.getValue(), "text/plain", Charset.forName("UTF-8")));
for(String file : files) {
reqEntity.addPart("file", new FileBody(new File(file)));
// 设置提交信息
HttpPost httppost = new HttpPost(url);
httppost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httppost);
// 若状态码为200 ok
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取出回应字串
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println("doPostJson response[" + url + "]: \n" + strResult);
return strR
System.out.println("doPost Error Response[" + url + "]: \n" + httpResponse.getStatusLine().toString());
} catch (Exception e) {
e.printStackTrace();
2.3 修改API帮助类ApiUtil
增加多附件测试方法
// 发布带附件信息
public static boolean uploadMessage(String status, List&String& files) {
return uploadMessage(status, null, files);
public static boolean uploadMessage(String status, String groupId, List&String& files) {
List&BasicNameValuePair& params = new ArrayList&BasicNameValuePair&(0);
params.add(new BasicNameValuePair("account_token", getToken()));
params.add(new BasicNameValuePair("status", status));
if(groupId!=null) {
params.add(new BasicNameValuePair("group_id", groupId));
String xml = HttpClientUtil.doPostUpload(API_URL + "/messages/upload", params, files);
if (!hasText(xml)) {
if (xml.indexOf("errorCode") == -1) {
2.4 修改ApiUtil中的测试方法
修改后的测试代码如下
public static void main(String[] argus) {
login("", "password");
List&String& files = new ArrayList&String& (0);
files.add("c:\\myimage.jpg");
files.add("c:\\dulala.txt");
uploadMessage("测试附件和图片上传1", "151", files);
2.5 运行测试
运行测试代码,带附件信息发布成功;
3、参考资料
[1] HttpClient中官方范例
    examples\org\apache\http\examples\entity\mime\ClientMultipartFormPost.java
[2] /blog/uploading-files-multipart-post-apache/
[3] http://blog.csdn.net/fengjia10/article/details/7315279
浏览: 260891 次
来自: 上海
不知怎么发了这些东西,楼主勿怪啊
楼主真厉害。学习了
yfjtd 写道楼主谢谢你的分享,你写的文章很受用,我有两个问 ...
楼主谢谢你的分享,你写的文章很受用,我有两个问题不明白:1、使用 HttpClient 4 进行文件上传 - 推酷
使用 HttpClient 4 进行文件上传
本教程我们将描述如何使用
HttpClient 4进行一次多文件上传操作
我们将使用&
&作为测试服务器,因为它是面向公众的,并且接受大多数类型的内容.
如果你想要深入学习并了解你可以使用&
HttpClient 做到的其它很棒的事情
&– 那就去看看
让我们开始研究研究&
MultipartEntityBuilder
&对象,来向一个Http实体添加成分,它在稍后将会被通过一个POST操作上传.
这是向一个
HttpEntity添加成分来表示表单的一般方法
示例 2.1. - 使用两个文本成分和一个文件上传一个表单
File file = new File(textFileName, ContentType.DEFAULT_BINARY);
HttpPost post = new HttpPost(&&);
FileBody fileBody = new FileBody(file);
StringBody stringBody1 = new StringBody(&Message 1&, ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 = new StringBody(&Message 2&, ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart(&upfile&, fileBody);
builder.addPart(&text1&, stringBody1);
builder.addPart(&text2&, stringBody2);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
请注意我们也通过制定将会被服务器使用到的ContentType值来实例化File对象.
同样还请注意&
&方法有两个参数,作用就像是表单的键值对&. 除非服务器端实际需要这些值并使用了这些参数名称,它们就是有干系的,否则它们就会被简单的忽略掉.
addBinaryBody
addTextBody
创建一个multipart实体更直接的方式就是使用&
addBinaryBody
AddTextBody
& 方法. 这些方法服务于上传文本,文件,字符数组和&
InputStream
&对象. 我们用了一个简单的例子来描述如何使用它们 .
示例 3.1. - 上传一个文本和一个文本文件部分
HttpPost post = new HttpPost(&&);
File file = new File(textFileName);
String message = &This is a multipart post&;
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(&upfile&, file, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody(&text&, message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
注意这里不需要&
StringBody
同样重要的是,大多数服务器不会检查文本体的&
ContentType&
addTextBody
&方法可能会忽略掉&
ContentType
addBinaryBody 的
&API 接受一个&
ContentType&
- 但是它也有可能从一个二进制体来创建实体,而对应名称的表单参数持有了这个文件. 如前面小节所述,如果ContentType值没有被指定,一些服务器将不会识别这个文件.
接下来,我们将一个zip文件作为一个&
InputStream 添加进来,
&而图片文件将会被作为File对象被添加进来:
示例 3.2. - 上传一个Zip文件,一个图片文件和一个文本
HttpPost post = new HttpPost(&&);
InputStream inputStream = new FileInputStream(zipFileName);
File file = new File(imageFileName);
String message = &This is a multipart post&;
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody
(&upfile&, file, ContentType.DEFAULT_BINARY, imageFileName);
builder.addBinaryBody
(&upstream&, inputStream, ContentType.create(&application/zip&), zipFileName);
builder.addTextBody(&text&, message, ContentType.TEXT_PLAIN);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
请注意ContentType值可以被动态创建,正如上面这个针对zip文件的示例中所示&.
最后,不是所有的服务器都接受&
InputStream
&部分. 我们在代码的第一行实体化的服务器可以接受&.
让我们现在来看看另外一个示例,&
addBinaryBody直接用于一个位数组&
示例 3.3. - 上传一个位数组和文本
HttpPost post = new HttpPost(&&);
String message = &This is a multipart post&;
byte[] bytes = &binary code&.getBytes();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(&upfile&, bytes, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody(&text&, message, ContentType.TEXT_PLAIN);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
ContentType
&- 它现在被指定为二进制数据.
本文呈现了&
MultipartEntityBuilder 作为一个灵活的对象提供了创建一个&
multipart 表单多种API.
示例同样也展示了如何使用HttpClient上传一个类似于表单实体的HttpEntity&.
这些示例的所有实现和代码块在&
&中可以找到 – 这是一个基于Eclipse的项目, 因此可以很容易的导入并运行.
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致

我要回帖

更多关于 multipartentity 的文章

 

随机推荐