by Eugen Paraschiv on May 23, 2014 in HttpClient

http://www.baeldung.com/httpclient-multipart-upload

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 to the main HttpClient tutorial.

2. Using the AddPart Method

Let’s start by looking at the MultipartEntityBuilder object to add parts to a Http entitywhich 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

File file = new File(textFileName, ContentType.DEFAULT_BINARY);
HttpPost post = new HttpPost("http://echo.200please.com");
FileBody fileBody = new FileBody(file);
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 = new StringBody("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, and InputStream objects. Lets illustrate how with simple examples.

Example 3.1. – Uploading Text and a Text File Part

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 also possible 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 the ContentTypevalue is not specified.

Next, we’ll add a zip file as an InputStream, while the image file will be added as Fileobject:

Example 3.2. – Uploading a Zip File, an Image File and a Text Part

HttpPost post = new HttpPost("http://echo.200please.com");
InputStream inputStream = new FileInputStream(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

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.

Multipart Upload with HttpClient 4--reference的更多相关文章

  1. 阿里云OSS Multipart Upload上传实例

    原来是用的PutObject()方式上传文件的,但是当文件比较大的时候,总是报一个对方强制关闭连接导致上传失败.PS:公司的网比较渣,10MB的文件都传不上去,搜了下,说使用Multipart Upl ...

  2. multipart upload

    org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nes ...

  3. Apache Http Client 4 上传多个文件 (示例代码可在 github 上找到)

    转自:http://www.baeldung.com/httpclient-multipart-upload Multipart Upload with HttpClient 4 1. Overvie ...

  4. Golang Multipart File Upload Example

    http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/ The Go language is ...

  5. HttpClient and FileUpload

    All communication over the Internet happens using a standard set of protocols, such as File Transfer ...

  6. HttpClient上传文件

    1.上传客户端代码: public static void upload() { CloseableHttpClient httpclient = HttpClients.createDefault( ...

  7. HttpClient详细解释

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  8. HttpClient使用详细教程

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  9. HttpClient用法--这一篇全了解(内含例子)

    HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也 ...

随机推荐

  1. 【Quick 3.3】资源脚本加密及热更新(三)热更新模块

    [Quick 3.3]资源脚本加密及热更新(三)热更新模块 注:本文基于Quick-cocos2dx-3.3版本编写 一.介绍 lua相对于c++开发的优点之一是代码可以在运行的时候才加载,基于此我们 ...

  2. 打死也不换系统?笑谈过气的Windows XP

    http://tech.qq.com/a/20131012/007336.htm 按照IT领域的“安迪-比尔定律”:软件和游戏不断生成过户需求,硬件则通过技术创新来消化这些需求,这个过程会刺激用户在电 ...

  3. Oracle EBS R12 WIP Component Issue&Return Process

    oracleassemblytransactionscomponentsjobsreference 目录(?)[-] 定义BOM 定义Routing 定义WIP Discrete Job 发料 Mat ...

  4. Running an etcd cluster on localhost

    Purpose Run a cluster on localhost while investigating etcd Use a static cluster (So we have no exte ...

  5. POJ_3273_Monthly_Expense_(二分,最小化最大值)

    描述 http://poj.org/problem?id=3273 共n个月,给出每个月的开销.将n个月划分成m个时间段,求m个时间段中开销最大的时间段的最小开销值. Monthly Expense ...

  6. c语言_文件操作_FILE结构体解释_涉及对操作系统文件FCB操作的解释_

    1. 文件和流的关系 C将每个文件简单地作为顺序字节流(如下图).每个文件用文件结束符结束,或者在特定字节数的地方结束,这个特定的字节数可以存储在系统维护的管理数据结构中.当打开文件时,就建立了和文件 ...

  7. C# GC.Collect()

    用C#写了一个运用ICE组件进行接口通信的服务程序,程序运行很正常,可是在客户端调用ICE接口时出现了大量的数据丢失,而且偶尔还通信不上,服务端最明显的现象就是telnet服务的通信端口时不通(cmd ...

  8. 彻底解决:请求被中止: 未能创建 SSL/TLS 安全通道

    最近有个项目要调用客户用java写的带https的webservice,对方提供了证书文件 test.pfx,我这里调用方式如下: //webservice代理类 SvcService svc = n ...

  9. 安卓使用WIFI调试程序

    不知怎么回事,USB老是掉,真心烦.于是想着用WIFI可不可以调试呢,去百度一搜,果然可以.下面我说一下我的方案. 1.使用APWIFI创建WIFI热点,用安卓手机连接该热点,试试手机可以上网不. 2 ...

  10. json-lib反序列化时(JSONObject.toBean),时间类型为空的处理

    需求: 在我们的项目里希望JsonString传入日期类型值为空时,JSONObject.toBean时可以将Java对象的该日期属性设为null. 解决过程: json-lib反序列化Json字符串 ...