Created
July 27, 2016 01:58
-
-
Save mandybess/dca2e8a0527aff2d8e0688c17297c945 to your computer and use it in GitHub Desktop.
How to send multiple query parameters of same name with Retrofit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Thanks, This is what I exactly needed
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
how to use
create an instance of your api service via the above
create()
method and pass in the dynamic query parameters:where
ApiService
is any retrofit interface 👯