Adding query parameters to single requests is straight forward. You’re using the @Query
annotation for your parameter declaration within the interface methods. This tells Retrofit to translate the provided query parameter name and value to the request and append the fields to the url. Recently, we’ve been asked how to add a query parameter to every request using an interceptor. If you’re having that same problem? This post is for you!
Retrofit Series Overview
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
Add Query Parameters
If you’ve used Retrofit before, you’re aware of the @Query
annotation used to add query parameters for single requests. There are situations where you want to add the same query parameter to every request, just like adding an Authorization
header to every request passing the authentication token. If you’re requesting an API which accepts an apikey
as a request parameter, it’s valuable to use an interceptor instead add the query parameter to every request method.
You can do that by adding a new request interceptor to the OkHttpClient
. Intercept the actual request and get the HttpUrl
. The http url is required to add query parameters since it will change the previously generated request url by appending the query parameter name and its value.
The following code illustrates the interceptor and we’ll explain the details below the snippet.
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("apikey", "your-actual-api-key")
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Once you’ve the HttpUrl
object, you can create a new builder based on the original http url object. The builder will let you add further query parameters using the .addQueryParameter(key, val)
method. Once you’ve added your query parameter, use the .build()
method to create the new HttpUrl
object which is added to the request by using the Request.Builder
. The code above builds the new request with the additional parameter based on the original request and just exchanges the url with the newly created one.
Outlook
The shown functionality to add request parameters within the OkHttp interceptor isn’t that obvious. If your API requires you to send the same query parameter with every request, it’s a very convenient way to shift the query parameter definition from the interface methods to a request interceptor.