转自: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.

最新文章

  1. 2、摘要函数——MD2/MD4/MD5数字签名
  2. LA 4329 Ping pong 树状数组
  3. java工程笔记
  4. [python拾遗]文件操作
  5. 通过 Code First 开发建立新数据库
  6. Android学习笔记之性能优化SparseArray
  7. Bootstrap3.0学习第二十三轮(JavaScript插件——警告框)
  8. Laravel5.1 启动详解
  9. jQuery编写的一款兼容IE6的图片轮播幻灯片
  10. SpringMvc入门三----控制器
  11. 【转】Kinect使用
  12. CSS 布局Float 【4】
  13. Servlet的学习之Request请求对象(3)
  14. TurnipBit—MicroPython开发板:妥妥拽拽零基础也能玩编程
  15. UML图学习之二 类图
  16. 算法:输出一个整数(不用ToString方法)
  17. <转载>ford-fulkerson算法2
  18. 阿里云的免费型DV SSL证书
  19. Jersey RESTful WebService框架学习(一)
  20. DOM4J对于XML的用法

热门文章

  1. 【ACM】hdu_zs2_1004_Problem D _201308030856
  2. mysqldump中使用flush tables with read lock的风险分析
  3. tcpip学习
  4. POJ 1155
  5. Lua5.2 请求 luasocket 相关模块时的 multiple-lua-vms-detected
  6. 沁园春·咏史
  7. 通过UrlRewriter配置MVC4伪静态
  8. PL/SQL Developer自己主动补全SQL语句
  9. bzoj5194: [Usaco2018 Feb]Snow Boots
  10. 各种编程语言功能综合简要介绍(C,C++,JAVA,PHP,PYTHON,易语言)