Multipart Upload with HttpClient 4--reference
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的更多相关文章
- 阿里云OSS Multipart Upload上传实例
原来是用的PutObject()方式上传文件的,但是当文件比较大的时候,总是报一个对方强制关闭连接导致上传失败.PS:公司的网比较渣,10MB的文件都传不上去,搜了下,说使用Multipart Upl ...
- multipart upload
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nes ...
- Apache Http Client 4 上传多个文件 (示例代码可在 github 上找到)
转自:http://www.baeldung.com/httpclient-multipart-upload Multipart Upload with HttpClient 4 1. Overvie ...
- Golang Multipart File Upload Example
http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/ The Go language is ...
- HttpClient and FileUpload
All communication over the Internet happens using a standard set of protocols, such as File Transfer ...
- HttpClient上传文件
1.上传客户端代码: public static void upload() { CloseableHttpClient httpclient = HttpClients.createDefault( ...
- HttpClient详细解释
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- HttpClient使用详细教程
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- HttpClient用法--这一篇全了解(内含例子)
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也 ...
随机推荐
- 学习笔记-[Maven实战]-第三章:Maven使用入门(2)
使用maven执行编译和测试 1.maven执行编译 (1).在pom.xml上点右键,选择Maven build... (2).在Goals里输入clean complie,执行编译 执行结果: [ ...
- noproguard.classes-with-local.dex
make: *** [out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/noproguard.classes-with-loca ...
- C# SerialPort的简单使用
SerialPort中串口数据的读取与写入有较大的不同.由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取.一.线程实时读串口:二.事件触发方式实现.由于线程实时读串口的效率不是十分高效 ...
- new Option及用法
op.sclassnumber.options.add(new Option(secondMenuClassNumber[0]+":"+secondMenuText[0]),se ...
- poj3037
首先到每个点的速度实际上是一个定值,就是v0*2^(起点与当前点高度差) 所以当前点i到任意一个相邻点的时间都是一个定值, 不难想到构图最短路径 ..] ,,,); dy:..] ,,-, ...
- split方法在低版本IE浏览器上无法解析的问题
前一篇不知道怎么被博客园给删了,重新补发一个. 最近在项目中发现一个很诡异的问题,通过js获取cookie时,发现赋给用户name的时候IE9和低于9以下的浏览器对比时获取到的名字不一样,通过调试发现 ...
- web移动开发最佳实践之html篇
一.前言 在目前的移动应用开发大潮下,使用web技术进行移动应用开发正变得越来越流行,它主要使用html5.css3.js等技术,在跨平台性.可移植性方面具有无可比拟的优势,特别适合开发对性能要求不太 ...
- android WebViewClient的方法解释
1.在点击请求的是链接是才会调用,重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边. public boolean shouldOverrideUrlLo ...
- ArrayList源码解析
ArrayList简介 ArrayList定义 1 public class ArrayList<E> extends AbstractList<E> implements L ...
- QT学习(对话框)codeblock版本
参考: http://www.cnblogs.com/JohnShao/archive/2011/09/26/2191627.html http://www.cnblogs.com/xiao-chen ...