使用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()
方法建立RequestBuilder
物件(型別為POST
)。並將想要傳送請求的Uri作為引數傳遞給它。
//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
第8步 - 將實體物件設定為RequestBuilder
使用RequestBuilder
類的setEntity()
方法將上面建立的multipart
實體設定為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": "217.216.100.180",
"url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK