Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add arguments to the end of a url in Retrofit

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?

like image 436
beechboy2000 Avatar asked Mar 09 '14 00:03

beechboy2000


People also ask

How do you send parameters in retrofit?

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 .

What is @query in retrofit?

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.


2 Answers

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);
    }
}
like image 181
Louis CAD Avatar answered Nov 15 '22 08:11

Louis CAD


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.

like image 23
Jake Wharton Avatar answered Nov 15 '22 09:11

Jake Wharton