LoginSignup
24
25

More than 5 years have passed since last update.

RetrofitでMultipartをらくらくPOST

Posted at

Square社のRetrofitはREST通信を簡潔に行うことができる出来た子ですが、いろいろと面倒なMultipartのPOST(PUT)送信も簡潔にできます。

いつもどおりにRestAdapterからAPIアクセス用のインスタンスを作成します。

final Executor executor = Executors.newCachedThreadPool();
final OkHttpClient okHttpClient = new OkHttpClient();
RestAdapter mRestAdapter = new RestAdapter.Builder()
    .setClient(new OkClient(okHttpClient))
    .setExecutors(executor, new MainThreadExecutor())
    .setEndpoint("https://api.hoge.com")
    .setRequestInterceptor(requestInterceptor)
    .setConverter(new GsonConverter(new Gson()))
    .build();
Api mApi = mRestAdapter.create(Api.class);

API通信側を作成。

Api.java
@Multipart
@POST("/upload")
void updateMultipart(
    @Header("Authorization") String token,              //ヘッダー
    @Part("fileContent") TypedFile file,                //単一ファイル
    @PartMap HashMap<String, TypedFile> fileParams,     //複数ファイル
    @Part("textContent") String text,                   //単一ファイル
    @PartMap HashMap<String, String> stringParams,      //複数テキスト
    Callback<MultipartResponse> callback                //非同期にしたいのでコールバックを渡す
    );

APIをコールします。


//複数ファイル用
HashMap<String, TypedFile> fileParam = new HashMap<String, TypedFile>();
//複数テキスト用
HashMap<String, String> stringParams = new HashMap<String, String>();

fileParam.put("fileContent1", new TypedFile("image/jpeg", new File(filePath1)));
fileParam.put("fileContent2", new TypedFile("image/jpeg", new File(filePath2)));

stringParams.put("textContent1", "text1");
stringParams.put("textContent2", "text2");

Api.updateMultipart(
        "token",
        new TypedFile("image/jpeg", new File(filePath)),
        fileParam,
        "hoge",
        stringParams,
        new Callback<CreateResponse>() {
            @Override
            public void success(MultipartResponse mMultipartResponse, Response response) {
                    //リクエスト成功
            }

            @Override
            public void failure(RetrofitError error) {
                    //リクエスト失敗
            }
        });

以前のAndroidでのMultipartリクエストに比べて随分と簡潔に記述できるようになったと思います。

24
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
25