Apache Httpclient 简明教程

Apache HttpClient - Multipart Upload

使用 HttpClient,我们可以执行多部分上传,即,我们可以将较大的对象上传为较小的部分。在本节中,我们通过上传一个简单的文本文件演示了 HTTP 客户端中的多部分上传。

通常,任何多部分上传都包含三个部分。

  1. Initiation of the upload

  2. Uploading the object parts

  3. Completing the Multipart upload

对于使用 HttpClient 的多部分上传,我们需要按照以下步骤进行:

  1. Create a multipart builder.

  2. 向其中添加所需部分。

  3. 完成构建并获取一个多部分 HttpEntity。

  4. 通过设置上述多部分实体来构建请求。

  5. Execute the request.

以下是使用 HttpClient 库上传多部分实体的步骤。

Step 1 - Create an HttpClient object

@ {s15}`类的@ {s14}`方法返回`@ {s16}`类的对象,该对象是 HttpClient 接口的基本实现。使用此方法,创建一个 HttpClient 对象 -

//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();

Step 2 - Create a FileBody object

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);

Step 3 - Create a MultipartEntityBuilder

MultipartEntityBuilder 类用于构建多部分 HttpEntity 对象。使用 create() 方法(同类方法)创建其对象。

//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();

Step 4 - Set the mode

MultipartEntityBuilder 有三种模式:严格模式、RFC6532 和 BROWSER_COMPATIBLE。使用 setMode() 方法将其设置为所需模式。

//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

Step 5 - Add various the desired parts

使用 addTextBody()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"));

Step 6 - Building single entity

可以使用 MultipartEntityBuilder 类的 build() 方法将所有这些部分构建成单个实体。使用此方法,将所有部分构建成单个 HttpEntity

//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entityBuilder.build();

Step 7 - Create a RequestBuilder object

RequestBuilder 类用于通过向其中添加参数来构建请求。如果请求类型为 PUT 或 POST,它会以 URL 编码实体的形式将参数添加到请求中。

使用 post() 方法创建 RequestBuilder 对象(类型为 POST)。并将要向其发送请求的 Uri 作为参数传递给它。

//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");

Step 8 - Set the entity object to the RequestBuilder

使用 RequestBuilder 类的 setEntity() 方法,将上面创建的多部分实体设置为 RequestBuilder。

//Setting the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);

Step 9 - Build the HttpUriRequest

使用 RequestBuilder 类的 build() 方法来构建 HttpUriRequest 请求对象。

//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();

Step 10 - Execute the request

使用 execute() 方法执行在上一步中构建的请求(将请求作为参数绕过此方法)。

//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);

Example

以下示例演示如何使用 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());
   }
}

Output

执行后,上述程序会生成以下输出−

{
   "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