转自:http://www.baeldung.com/httpclient-multipart-upload

Multipart Upload with HttpClient 4

1. Overview

In this tutorial we will illustrate how to do a multipart upload operation using HttpClient 4.

We’ll use http://echo.200please.com as a test server because it’s public and it accepts most types of content.

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over tothe
main HttpClient tutorial
.

2. Using the AddPart Method

Let’s start by looking at the MultipartEntityBuilder object to
add parts to a Http entity
which will then be uploaded via a POST operation.

This is a generic method to add parts to an HttpEntity representing the form.

Example 2.1. – Uploading a Form with Two Text Parts and a File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
File file =
new File(textFileName, ContentType.DEFAULT_BINARY);
HttpPost post =
new HttpPost("http://echo.200please.com");
FileBody fileBody =newFileBody(file);
StringBody stringBody1 =newStringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 =newStringBody("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);

Note that we’re instantiating the File object by also specifying the
ContentType
value to be used by the server.

Also, note that the addPart method has two arguments, acting like
key/value
pairs for the form. These are only relevant if the server side actually expects and uses parameter names – otherwise they’re simply ignored.

3. Using the addBinaryBody and addTextBody Methods

A more direct way to create a multipart entity is to use the addBinaryBody andAddTextBody methods. These methods work for uploading text, files, character arrays, andInputStream objects. Lets illustrate how with simple examples.

Example 3.1. – Uploading Text and a Text File Part

1
2
3
4
5
6
7
8
9
10
11
HttpPost post =
new HttpPost("http://echo.200please.com");
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);

Note that the FileBody and StringBody objects are not needed here.

Also important, most servers do not check the ContentType of the text body, so theaddTextBody method may omit the ContentType value.

The addBinaryBody API accepts a ContentType – but it is alsopossible to create the entity just from a binary body and the name of the form parameter holding the file. As stated in the previous section some servers will not recognize
the file if theContentType value is not specified.

Next, we’ll add a zip file as an InputStream, while the image file will be added asFile object:

Example 3.2. – Uploading a Zip File, an Image File and a Text Part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HttpPost post =
new HttpPost("http://echo.200please.com");
InputStream inputStream =newFileInputStream(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);

Note that the ContentType value can be created on the fly, as is the case in the example above for the zip file.

Finally, not all servers acknowledge InputStream parts. The server we instantiated in the first line of the code recognizes InputStreams.

Let’s now look at another example where addBinaryBody is working directly with a byte array :

Example 3.3. – Uploading a Byte Array and Text

1
2
3
4
5
6
7
8
9
10
11
12
HttpPost post =
new HttpPost("http://echo.200please.com");
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);

Notice the ContentType – which is now specifying binary data.

4. Conclusion

This article has presented the MultipartEntityBuilder as a flexible object which offer multiple API choices to create a multipart form.

The examples have also shown how to use the HttpClient to upload
a HttpEntity
that similar to a form entity.

The implementation of all these examples and code snippets can be found in 
my github project
  – this is an Eclipse based project, so it should be easy to import and run as it is.

Apache Http Client 4 上传多个文件 (示例代码可在 github 上找到)的更多相关文章

  1. JAVA通过FTP方式向远程服务器或者客户端上传、下载文件,以及删除FTP服务器上的文件

    1.在目标服务器上搭建FTP服务器 搭建方式有多种大家可以自行选择,例如使用Serv-U或者FTPServer.exe:这里我以FTPServer.exe为例搭建:在目标服务器(这里对应的IP是10. ...

  2. PHP同时上传“多个”文件示例,并格式化$_FILES数组信息

    方法1: 在html表单,放置多个文件选择框, 使用数组名作为组件的名字,如下: <form action="upload.php" method="post&qu ...

  3. java Ftp上传创建多层文件的代码片段

    StringBuilder sBuilder = new StringBuilder();            String[] pah = path.split("/");   ...

  4. 每天一个linux命令(26):用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  5. 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  6. 用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  7. linux常用命令:用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  8. 【转】每天一个linux命令(26):用SecureCRT来上传和下载文件

    原文网址:http://www.cnblogs.com/peida/archive/2012/11/28/2793181.html 用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接 ...

  9. PHP实现文件上传和下载(单文件上传、多文件上传、多个单文件上传)(面向对象、面向过程)

    今天我们来学习用PHP进行文件的上传和下载,并且用面向过程和面向对象的方式对文件上传进行一个限制 一.简单的上传测试 1.客户端:upload.php 2.后端:doAction.php 结果: 二. ...

随机推荐

  1. Html5最简单的游戏Demo——Canvas绘图的骰子

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...

  2. [bzoj1610][Usaco2008 Feb]Line连线游戏_暴力枚举

    Line连线游戏 bzoj-1610 Usaco-2008 Feb 题目大意:Farmer John最近发明了一个游戏,来考验自命不凡的贝茜.游戏开始的时 候,FJ会给贝茜一块画着N (2 <= ...

  3. TensorFlow 入门之手写识别CNN 三

    TensorFlow 入门之手写识别CNN 三 MNIST 卷积神经网络 Fly 多层卷积网络 多层卷积网络的基本理论 构建一个多层卷积网络 权值初始化 卷积和池化 第一层卷积 第二层卷积 密集层连接 ...

  4. WindowsclientC/C++编程规范“建议”——函数

    1 函数 1.1 代码行数控制在80行及以内 等级:[要求] 说明:每一个函数的代码行数控制应该控制在80行以内.假设超过这个限制函数内部逻辑一般能够拆分.假设试图超过这个标准.请列出理由. 但理由不 ...

  5. vim 插件配置博客记录

    本来打算自己写下各种经常使用vim的插件安装方法, 可是搜索了下, 发现别人都写过了, 在写一遍也没有意思, 特此记录. Vim 经常使用命令 http://blog.csdn.net/hittata ...

  6. spring学习笔记(22)声明式事务配置,readOnly无效写无异常

    在上一节内容中.我们使用了编程式方法来配置事务,这种优点是我们对每一个方法的控制性非常强.比方我须要用到什么事务,在什么位置假设出现异常须要回滚等.能够进行非常细粒度的配置.但在实际开发中.我们可能并 ...

  7. C 中 main 函数的參数

          看到不同的人写出的 C 或者 C++ 程序时,可能会出现不一样的 main 函数的定义,以下的几种定义方式都是对的: int main(void) int main(int argc) i ...

  8. Linux - 目录结构与查看,复制,删除,剪切指令

    Linux当中,一切皆文件. Linux目录结构 / 根分区,只有root用户对此目录拥有写权限. /etc 配置文件 /boot 启动文件 /var 可增长的目录 .日志,文件等. /root 管理 ...

  9. 谈谈JavaScript深浅拷贝

    浅拷贝 function shallowCopy(source){ var newObj = {}; for(var attr in source){ newObj[attr] = source[at ...

  10. POJ3414 Pots

    题目: 给你两个容器,分别能装下A升水和B升水,并且可以进行以下操作 FILL(i)        将第i个容器从水龙头里装满(1 ≤ i ≤ 2); DROP(i)        将第i个容器抽干 ...