Apache-httpclient-multipart-upload
提供:Dev Guides
Apache HttpClient-マルチパートアップロード
HttpClientを使用して、マルチパートアップロードを実行できます。つまり、大きなオブジェクトを小さなパーツにアップロードできます。 この章では、単純なテキストファイルをアップロードすることにより、HTTPクライアントでのマルチパートアップロードを示します。
一般に、マルチパートアップロードには3つのパートが含まれます。
- アップロードの開始
- オブジェクトパーツのアップロード
- マルチパートアップロードの完了
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の3つのモードがあります。 * 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