Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 addQueryParam replacement

In previous retrofit versions it was possible to add an interceptor and use that to add query parameters that were globally needed for example:

 .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade requestFacade) {
                        requestFacade.addQueryParam("platform", "android");
                        requestFacade.addQueryParam("app_version", com.package.BuildConfig.VERSION_NAME);


                }
            })

With the new implementation, it's required that you use OkHttpClient.interceptors. With this new approach, how would one append parameters without removing the original paramaters?

like image 303
Nic Capdevila Avatar asked Dec 30 '25 01:12

Nic Capdevila


1 Answers

Here is an okhttp implementation --

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.httpUrl().newBuilder()
                     .addQueryParameter("platform", "android")
                     .addQueryParameter("app_version", com.package.BuildConfig.VERSION_NAME)
                     .build();
        Request newRequest = chain.request().newBuilder().url(url).build();
        return chain.proceed(newRequest);
    }
});

Add the client to your retrofit --

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://www.example.com")
    .client(client)         
    .build();
like image 68
iagreen Avatar answered Jan 03 '26 00:01

iagreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!