Skip to content

Instantly share code, notes, and snippets.

@mandybess
Created July 27, 2016 01:58
Show Gist options
  • Select an option

  • Save mandybess/dca2e8a0527aff2d8e0688c17297c945 to your computer and use it in GitHub Desktop.

Select an option

Save mandybess/dca2e8a0527aff2d8e0688c17297c945 to your computer and use it in GitHub Desktop.

Revisions

  1. Amanda Hill created this gist Jul 27, 2016.
    52 changes: 52 additions & 0 deletions RestClient.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    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);
    }
    }
    }