Updated 9 October 2017
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
1 2 3 4 5 6 |
@FormUrlEncoded @POST("/your_api") Call<ResponseBody> methodName( @Query("param1") String param1, @Field("param2") int param2, @Field("param3") String param3); |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("key", "value") .build(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .url(url); Request request = requestBuilder.build(); return chain.proceed(request); } }); |
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.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.