Apache Http Client 4 上传多个文件 (示例代码可在 github 上找到)
转自: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);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
|
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
|
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"),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
|
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 上找到)的更多相关文章
- JAVA通过FTP方式向远程服务器或者客户端上传、下载文件,以及删除FTP服务器上的文件
1.在目标服务器上搭建FTP服务器 搭建方式有多种大家可以自行选择,例如使用Serv-U或者FTPServer.exe:这里我以FTPServer.exe为例搭建:在目标服务器(这里对应的IP是10. ...
- PHP同时上传“多个”文件示例,并格式化$_FILES数组信息
方法1: 在html表单,放置多个文件选择框, 使用数组名作为组件的名字,如下: <form action="upload.php" method="post&qu ...
- java Ftp上传创建多层文件的代码片段
StringBuilder sBuilder = new StringBuilder(); String[] pah = path.split("/"); ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- 用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- linux常用命令:用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- 【转】每天一个linux命令(26):用SecureCRT来上传和下载文件
原文网址:http://www.cnblogs.com/peida/archive/2012/11/28/2793181.html 用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接 ...
- PHP实现文件上传和下载(单文件上传、多文件上传、多个单文件上传)(面向对象、面向过程)
今天我们来学习用PHP进行文件的上传和下载,并且用面向过程和面向对象的方式对文件上传进行一个限制 一.简单的上传测试 1.客户端:upload.php 2.后端:doAction.php 结果: 二. ...
随机推荐
- [WordPress]基本操作
编辑文本 文本模式下 more 提取摘要<!--more-->
- matplotlib的cmap
今天又看到了这样的代码: plt.imshow(X_train[0], cmap=plt.get_cmap('PuBuGn_r')) #plt.imshow(X_train[0], cmap=plt. ...
- Linux命令(九)——系统监视和进程控制
与windows系统一样,linux系统中也有很多进程在同时运行,每个进程都有一个识别码PID,它是进程的唯一识别标志. 一.进程的类型 1.系统进程 在操作系统启动后,系统环境平台运行所加载的进程, ...
- Android利用Intent与其它应用交互
前言: 上一篇博客给大家聊了Intent的定义.分类.属性和功能,相信大家对于Intent在Android中的作用已经清楚,这一篇博客将会给大家聊Intent的使用方法. Android系统的一个重要 ...
- C C++每个头文件的功能说
C/C++每个头文件的功能说明 传统 C++ #include <assert.h> //设定插入点 #include <ctype.h> //字符处理 #include &l ...
- Linux - Nginx配置反向代理。
Nginx配置反向代理. 准备两台服务器 http://192.168.70.66 http://192.168.70.62 设置正则匹配(192.168.70.66) vim /usr/local/ ...
- 高效管理 Elasticsearch 中基于时间的索引——本质是在利用滚动模式做数据的冷热分离,热索引可以用ssd
高效管理 Elasticsearch 中基于时间的索引 转自:http://stormluke.me/es-managing-time-based-indices-efficiently/ 用 Ela ...
- 【读书笔记】UEFI原理与编程(1)概述及开发环境的搭建
一.概述: 0.为什么会有这篇文章 说实在的,在2016初的时候,我就萌生了写一个操作系统的念头,但是这对于我一个菜鸟来说,犹如登天. 既然想了就去写,即使最后做不完,也不后悔. 抱着这样的念头,我开 ...
- caffe 参数介绍 solver.prototxt
转载自 http://blog.csdn.net/cyh_24/article/details/51537709 solver.prototxt net: "models/bvlc_alex ...
- shell 杂集
1.shell 相等比较注意 -eq 数字相等的比较 == 字符串相等的比较 2.== 和 = 的区别 == 可用于判断变量是否相等,= 除了可用于判断变量是否相等外,还可以表示赋值. = 与 == ...