So, I'm trying to make a REST request that looks like this: https://api.digitalocean.com/droplets/?client_id=[client_id]&api_key=[api_key]
Where https://api.digitalocean.com
is the endpoint, and @GET("/droplets/")
would be the annotation. I would like the end bit to be added automatically, since it would be identical for any API requests I make, and it would be a hassle to add it to each request. Is there any way to do that?
You can pass parameter by @QueryMap Retrofit uses annotations to translate defined keys and values into appropriate format. Using the @Query("key") String value annotation will add a query parameter with name key and the respective string value to the request url .
Retrofit uses @Query annotation to define query parameters for requests. Query parameters are defined before method parameters. In annotation, we pass the query parameter name which will be appended in the URL.
Here's my interceptor for Retrofit 2:
private static class AuthInterceptor implements Interceptor {
private String mApiKey;
public AuthInterceptor(String apiKey) {
mApiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().httpUrl()
.newBuilder()
.addQueryParameter("api_key", mApiKey)
.build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
}
}
Pass a RequestInterceptor
instance to the RestAdapter.Builder
which adds the query parameters.
Retrofit will invoke the request interceptor for every API call which allows you to append query parameters or replace path elements.
In this callback you will be able to append the clientId
and apiKey
query parameters for every request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With