Skip to content

Instantly share code, notes, and snippets.

@mandybess
Created July 27, 2016 01:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandybess/dca2e8a0527aff2d8e0688c17297c945 to your computer and use it in GitHub Desktop.
Save mandybess/dca2e8a0527aff2d8e0688c17297c945 to your computer and use it in GitHub Desktop.
How to send multiple query parameters of same name with Retrofit
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import okhttp3.HttpUrl;
import okhttp3.HttpUrl.Builder;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
public class RestClient {
private static final String BASE_URL = "www.base.com";
public static <T> T create(Class<T> apiInterfaceClass, Map<String, List<String>> queries) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient(queries))
.build();
return retrofit.create(apiInterfaceClass);
}
private static OkHttpClient okHttpClient(Map<String, List<String>> queries) {
return new OkHttpClient.Builder()
.addInterceptor(makeQueriesInterceptor(queries))
.build();
}
private static Interceptor makeQueriesInterceptor(Map<String, List<String>> queries) {
return chain -> {
HttpUrl url = addQueryParametersToUrl(chain.request().url(), queries);
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
};
}
private static HttpUrl addQueryParametersToUrl(HttpUrl url, Map<String, List<String>> queries) {
HttpUrl.Builder builder = url.newBuilder();
for (Entry<String, List<String>> entry : queries.entrySet()) {
addQueryParameters(builder, entry);
}
return builder.build();
}
private static void addQueryParameters(Builder builder, Entry<String, List<String>> entry) {
String key = entry.getKey();
List<String> value = entry.getValue();
for (String option : value) {
builder.addQueryParameter(key, option);
}
}
}
@mandybess
Copy link
Author

how to use

create an instance of your api service via the above create() method and pass in the dynamic query parameters:

ApiService service = RestClient.create(ApiService.class, queries);

where ApiService is any retrofit interface 👯

@kabindra
Copy link

kabindra commented Aug 6, 2016

Thanks, This is what I exactly needed

Copy link

ghost commented May 11, 2017

Thank you, Amanda!
helpful and easy-to-use.

I would like to change only ine thing - pass base_url as an argument in create() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment