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 结果: 二. ...
随机推荐
- LeetCode之RemoveElement
题目: Given an array and a value, remove all instances of that value in place and return the new lengt ...
- 手把手实现Java权限(1)-Shiro介绍
功能介绍 Authentication :身份认证/登录.验证用户是不是拥有对应的身份: Authorization :授权,即权限验证.验证某个已认证的用户是否拥有某个权限:即推断用 户能否做事 ...
- 关于BeanShell报错提示Error invoking bsh method
背景:因测试需要打算从外部引用.java和.class文件,奈何报错挥之不去:Error invoking bsh method: eval...... 各种百度取经之后,决定先抛弃引用,试试Bean ...
- 数据结构之---C语言实现广义表头尾链表存储表示
//广义表的头尾链表存储表示 //杨鑫 #include <stdio.h> #include <malloc.h> #include <stdlib.h> #in ...
- 关系型数据库与HBase的数据储存方式差别
现在Bigtable型(列族)数据库应用越来越广,功能也非常强大. 可是非常多人还是把它当做关系型数据库在使用,用原来关系型数据库的思维建表.存储.查询. 本文以hbase举例讲述数据模式的变化. 传 ...
- makepy
文件连接: https://files.cnblogs.com/files/mophy/%E7%99%BB%E5%BD%95%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90.7 ...
- element-UI中table表格的row-click事件怎么获取一行数据的id
<el-table :data="tableData" style="width: 100%" @row-click="openDetails( ...
- hdoj--5093--Battle ships(二分图经典建图)
Battle ships Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Tot ...
- 软件开发 —— 极限编程(XP:Extreme Programming)
1. 软件开发的基本概念 软件开发的过程是:需求分析.设计.编码和测试. 2. 极限编程基本内涵 极限编程是一个轻量级的.灵巧的软件开发方法:同时它也是一个非常严谨和周密的方法. 它的基础和价值观是交 ...
- Object源码分析(一)
刚注册博客,准备学习一下java源码,当然首先从Object看起. 介绍一下Object: Object是所有类层次结构的根,所有的类都将Object作为超类.所有的对象,包括数组,都实现了Objec ...