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
廣告