Start a Project

Add query parameters to all Retrofit HTTP requests

Nowadays Retrofit is one of the most popular libraries in Android for HTTP requests. These requests contain parameters like Body, Field, Query etc. If you are looking to add some default query parameters in your every request then we are going to discuss that in this blog.

Consider the below example

As you can see in the above request, it contains a query parameter. This is one way of adding a query parameter to your request. But if you want the same parameter in every request then you will have to add the query parameter manually in every request which is obviously redundant or you can do it by using Interceptor.

Interceptors actually intercept the request and modify or change them according to your need. To add query parameters you need to intercept the OkHttpClient and get the HttpUrl. Using the HttpUrl object you can append additional query parameters by using the addQueryParameter function. It will not disturb the already existing parameters

Let us look at an example on how you can do it. Consider the below code

As you can see we have added an interceptor to the OkHttpClient and used chain.request() to get the original request and us it to the HttpUrl. Then we have created a new HttpUrl object using the original HttpUrl and used the addQueryParameter() function to add the query parameter to all the requests. Now create a new Request, add the HttpUrl to it, and use chain.proceed() to hit the request with the newly created request.

Thank you very much. This is Vedesh Kumar signing off.

Exit mobile version