Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

前回書いた【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)
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away