转自: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. (15)Spring Boot使用Druid和监控配置【从零开始学Spring Boot】

    Spring Boot 系列博客] 更多查看博客:http://412887952-qq-com.iteye.com/blog Spring Boot默认的数据源是:org.apache.tomcat ...

  2. 0301mysql数据库建表情况

    转自博客:http://blog.csdn.net/dreamcode/article/details/8557197 一. 表设计 库名.表名.字段名必须使用小写字母,“_”分割. 库名.表名.字段 ...

  3. javascript Prototype constructor的理解(转)

    讲JS的构造的,这个比较清晰,但并不表示一定正确. 这几天一直在思考这个东东,感觉比以前理解更深入了. http://blog.csdn.net/chunqiuwei/article/details/ ...

  4. POJ 1984

    我做过的最棘手的一道题了,不是因为难,难就是不懂,而是因为明明思路对了,却调了很久程序没发现自己哪错了.....就连样例都不过 操,别人的代码::::::::::::::::::::::::::::. ...

  5. HDU 1240

    #include <iostream> #include <cstdio> using namespace std; ; char maze[MAX][MAX][MAX]; s ...

  6. [NOIP 2017] 奶酪

    [题目链接] http://uoj.ac/problem/332 [算法] 直接搜索即可 注意使用long long [代码] #include<bits/stdc++.h> using ...

  7. nginx FastCGI模块(FastCGI)配置

    http://www.howtocn.org/nginx:nginx%E6%A8%A1%E5%9D%97%E5%8F%82%E8%80%83%E6%89%8B%E5%86%8C%E4%B8%AD%E6 ...

  8. 南海区行政审批管理系统接口规范v0.3(规划)4.1.【queryAcceptById】业务明细查询

    加密前:{"time":"1510061005493","username":"GH_DATA_EXCHANGE",&q ...

  9. Python 3.x 判断 dict 是否包含某个键

    Python 3.x不再支持 has_key() 函数,而被__contains__('key')所替代,会返回bool,可以用其做判断. 代码示例: >>> user = 'dad ...

  10. mysql 1862 密码过期

    1.管理员权限运行命令: cmd mysqladmin -uroot -p password 修改密码. 2.设置密码永不过期. mysql 数据库\ user 表\ password_expired ...