jpotts18 jpotts18 - 7 months ago 28
Java Question

Android Retrofit Parameterized @Headers

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

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());
            }                    
        }
    });