Apache HttpClient - 分块上传
使用 HttpClient,我们可以执行分块上传,即我们可以将较大的对象分成较小的部分进行上传。在本章中,我们将通过上传一个简单的文本文件来演示 HTTP 客户端中的分块上传。
一般来说,任何分块上传都包含三个部分。
初始化上传
上传对象部分
完成分块上传
对于使用 HttpClient 进行分块上传,我们需要遵循以下步骤 -
创建一个分块构建器。
向其中添加所需的部分。
完成构建并获取一个分块 HttpEntity。
通过设置上述分块实体来构建请求。
执行请求。
以下是使用 HttpClient 库上传分块实体的步骤。
步骤 1 - 创建一个 HttpClient 对象
HttpClients 类的 createDefault() 方法返回一个 CloseableHttpClient 类的对象,它是 HttpClient 接口的基本实现。使用此方法,创建一个 HttpClient 对象 -
//Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault();
步骤 2 - 创建一个 FileBody 对象
FileBody 类表示由文件支持的二进制主体部分。通过传递一个 File 对象和一个表示内容类型的 ContentType 对象来实例化此类。
//Creating a File object
File file = new File("sample.txt");
//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
步骤 3 - 创建一个 MultipartEntityBuilder
MultipartEntityBuilder 类用于构建多部分 HttpEntity 对象。使用 create() 方法(同一类)创建其对象。
//Creating the MultipartEntityBuilder MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
步骤 4 - 设置模式
MultipartEntityBuilder 有三种模式:STRICT、RFC6532 和 BROWSER_COMPATIBLE。使用 setMode() 方法将其设置为所需的模式。
//Setting the mode entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
步骤 5 - 添加各种所需的部分
使用 addTextBody()、addPart() 和 addBinaryBody() 方法,您可以将简单的文本、文件、流和其他对象添加到 MultipartBuilder 中。使用这些方法添加所需的内容。
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));
步骤 6 - 构建单个实体
您可以使用 MultipartEntityBuilder 类的 build() 方法将所有这些部分构建成单个实体。使用此方法,将所有部分构建成单个 HttpEntity。
//Building a single entity using the parts HttpEntity mutiPartHttpEntity = entityBuilder.build();
步骤 7 - 创建一个 RequestBuilder 对象
RequestBuilder 类用于通过向其添加参数来构建请求。如果请求类型为 PUT 或 POST,则它会将参数作为 URL 编码实体添加到请求中。
使用 post() 方法创建一个(类型为 POST)RequestBuilder 对象。并将您想要发送请求到的 Uri 作为参数传递给它。
//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
步骤 8 - 将实体对象设置为 RequestBuilder
使用 RequestBuilder 类的 setEntity() 方法将上面创建的分块实体设置为 RequestBuilder。
//Setting the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity);
步骤 9 - 构建 HttpUriRequest
使用 RequestBuilder 类的 build() 方法构建一个 HttpUriRequest 请求对象。
//Building the request HttpUriRequest multipartRequest = reqbuilder.build();
步骤 10 - 执行请求
使用 execute() 方法执行上一步中构建的请求(通过将请求作为参数传递给此方法)。
//Executing the request HttpResponse httpresponse = httpclient.execute(multipartRequest);
示例
以下示例演示了如何使用 HttpClient 库发送分块请求。在此示例中,我们尝试发送一个由文件支持的分块请求。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
public class MultipartUploadExample {
public static void main(String args[]) throws Exception{
//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating a file object
File file = new File("sample.txt");
//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entitybuilder.build();
//Building the RequestBuilder request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
//Set the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);
//Printing the status and the contents of the response
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
System.out.println(httpresponse.getStatusLine());
}
}
输出
执行上述程序后,将生成以下输出 -
{
"args": {},
"data": "",
"files": {
"image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE
lFTkSuQmCC"
},
"form": {
"sample_text": "This is the text part of our file"
},
"headers": {
"Accept-Encoding": "gzip,deflate",
"Connection": "close",
"Content-Length": "11104",
"Content-Type": "multipart/form-data;
boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
},
"json": null,
"origin": "117.216.245.180",
"url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK