Android Retrofit Parameterized @Headers

jpotts18 picture jpotts18 · Aug 28, 2013 · Viewed 76k times · Source

I am using OAuth and I need to put the OAuth token in my header every time I make a request. I see the @Header annotation, but is there a way to make it parameterized so i can pass in at run time?

Here is the concept

@Header({Authorization:'OAuth {var}', api_version={var} })

Can you pass them in at Runtime?

@GET("/users")
void getUsers(
    @Header("Authorization") String auth, 
    @Header("X-Api-Version") String version, 
    Callback<User> callback
)

Answer

Felix picture Felix · Dec 10, 2013

Besides using @Header parameter, I'd rather use RequestInterceptor to update all your request without changing your interface. Using something like:

RestAdapter.Builder builder = new RestAdapter.Builder()
    .setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Accept", "application/json;versions=1");
            if (isUserLoggedIn()) {
                request.addHeader("Authorization", getToken());
            }                    
        }
    });

p/s : If you are using Retrofit2, you should use Interceptor instead of RequestInterceptor

Since RequestInterceptor is not longer available in Retrofit 2.0