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 结果: 二. ...
随机推荐
- owin--Authentication
下面的这个从httpcontext取出来的GetOwinContext的Authentication认证有很多关于cookie和session的方法,好像不实用owin也能取出来 private IA ...
- SPOJ 10628 Count on a tree (lca+主席树)
题意:给定一棵有n个结点的树,每一个点有一个权值.共同拥有m个询问.对于每一个询问(u,v,k),回答结点u至v之间第k小的点的权值. 思路:主席树+lca.首先指定一个根结点dfs一次并在此过程中建 ...
- 虚拟机window7与主机之间文件复制设置
一.需要安装VMware Tools 选中虚拟机>虚拟机>安装VMware Tools 一直点击下一步直至完成 二.设置文件共享 选定实体机需要共享给虚拟机的文件夹,并为该共享起一个名称. ...
- luogu3769 【模板】AC自动机(加强版)
题目大意:有N个由小写字母组成的模式串以及一个文本串T.每个模式串可能会在文本串中出现多次.你需要找出哪些模式串在文本串T中出现的次数最多. 对每个模式串建立一个Trie树.定义一个节点的Fail指针 ...
- vim插件系列
http://foocoder.com/blog/mei-ri-vimcha-jian-ping-hua-gun-dong-accelerated-smooth-scroll-dot-vim.html ...
- bzoj5178: [Jsoi2011]棒棒糖
就是裸的主席树嘛... 表扬一下自己1A #include<cstdio> #include<iostream> #include<cstring> #includ ...
- hdu 1085(普通母函数)
Holding Bin-Laden Captive! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Ja ...
- WebP 文件及其编码解码工具(WebPconv)
1. webp 文件 与JPEG相同,WebP 是一种有损压缩利用预测编码技术. WebP 是 Google 新推出的影像技术,它可让网页图档有效进行压缩,同时在质量相同的情况下,WebP 格式图像的 ...
- [POJ 3621] Sightseeing Cows
[题目链接] http://poj.org/problem?id=3621 [算法] 01分数规划(最优比率环) [代码] #include <algorithm> #include &l ...
- 写个js 分页玩玩(原创)
<ul id="page"> <li class="pagetest">1</li> <li class=" ...