LoginSignup
4
4

More than 5 years have passed since last update.

【Android】RetrofitのGETリクエストで配列を☆複数☆渡したい

Last updated at Posted at 2016-02-19

前回書いた【Android】RetrofitのGETリクエストで配列を渡したいでは、複数の配列を渡すという要件が満たせない。

Parameters: {"hoges"=>["1", "2", "3"]}
は、可能だけど、
Parameters: {"hoges"=>["1", "2", "3"], "fugas"=>["4", "5"]}
は、下記のやり方だとできない。

ダメな例
@Query("hoges[]") String... hoges, @Query("fugas[]") String... fugas

可変長引数は、パラメーター宣言の最後でしか使えないので、これはコンパイル不可。

なので、必要なパラメーター文字列を自力で作るしかなさそう。
渡す文字列は、@EncodedQueryでエンコードしてやる必要がある。

インターフェース側
@GET("/hogefugas.json")
public Observable<Data> getData(
         @EncodedQuery("hoges[]") String hoges,
         @EncodedQuery("fugas[]") String fugas);
呼び出し側
String[] hoges = {"1", "2", "3"};
String[] fugas = {"4", "5"};
// パラメータ文字列を作成
String hogeParameter = null;
String fugaParameter = null;
StringBuilder sbHoge = new StringBuilder();
StringBuilder sbFuga = new StringBuilder();
for (String hoge : hoges) {
  if(sbHoge.length() == 0) {
    sbHoge.append(hoge);
  } else {
    sbHoge.append("&hoges[]=");
    sbHoge.append(hoge);
}
for (String fuga : fugas) {
  if(sbFuga.length() == 0) {
    sbFuga.append(fuga);
  } else {
    sbFuga.append("&fugas[]=");
    sbFuga.append(fuga);
}
hogeParameter = new String(sbHoge);
fugaParameter = new String(sbFuga);

// Retrofit + RxAndroid
observable = restAdapter.create(RetrofitApi.class)
                    .getData(hogeParameter, fugaParameter);
生成されるリクエスト
/hogefugas.json?hoges[]=1&hoges[]=2&hoges[]=3&fugas[]=4&fugas[]=5

追記

https://github.com/square/retrofit/issues/1479
@EncodedQueryはRetrofit2.0でdepracateなので、こっちになるらしい。

@Query(encoded = true)
4
4
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
4
4