87

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
)
4
  • Did you ever figure this out? I need to pass in a token in the header also Sep 11, 2013 at 15:40
  • I am also looking for a solution to this, from documentation it sounds like @Headers() annotation on the method adds fields to header one by one, but only supports literals. And @Header("parameter") String string parameter annotation replaces the header with the supplied value.
    – nana
    Sep 12, 2013 at 1:02
  • 2
    Same here, couldn't find out how to handle sessions when using retrofit.
    – frankelot
    May 27, 2014 at 2:21
  • We did not need to pass all items, retrofit itself handle all. Please check my answer link in StackOverflow.
    – Subin Babu
    Apr 21, 2018 at 7:07

4 Answers 4

100

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

3
  • 3
    This is not directly related but if you find yourself needing to get values from the request object in order to generate your Authorization header, you'll need to extend ApacheClient and in execute duplicate the Request object (List<Header> headers = ...; Request requestNew = new Request(request.getMethod(), request.getUrl(), headers, request.getBody()); request = requestNew).
    – user153275
    Jan 7, 2014 at 18:14
  • 1
    That's a trick that messes a coded up, better use @nana's answer Mar 23, 2016 at 11:32
  • 1
    RestAdapter depends on Retrofit1, in Retrofit2 it is Retrofit. Im going to use Retrofit2, so it no issues if use RequestInterceptor as above code?
    – Huy Tower
    Sep 16, 2016 at 9:12
56

Yes, you can pass them in runtime. As a matter of fact, pretty much exactly as you typed it out. This would be in your API interface class, named say SecretApiInterface.java

public interface SecretApiInterface {

    @GET("/secret_things")
    SecretThing.List getSecretThings(@Header("Authorization") String token)

}

Then you pass the parameters to this interface from your request, something along those lines: (this file would be for example SecretThingRequest.java)

public class SecretThingRequest extends RetrofitSpiceRequest<SecretThing.List, SecretApiInteface>{

    private String token;

    public SecretThingRequest(String token) {
        super(SecretThing.List.class, SecretApiInterface.class);
        this.token = token;
    }

    @Override
    public SecretThing.List loadDataFromNetwork() {
        SecretApiInterface service = getService();
        return service.getSecretThings(Somehow.Magically.getToken());
    }
}

Where Somehow.Magically.getToken() is a method call that returns a token, it is up to you where and how you define it.

You can of course have more than one @Header("Blah") String blah annotations in the interface implementation, as in your case!

I found it confusing too, the documentation clearly says it replaces the header, but it DOESN'T!
It is in fact added as with @Headers("hardcoded_string_of_liited_use") annotation

Hope this helps ;)

1
  • 1
    I found in the docs that it doesn't replace an existing header: "Note that headers do not overwrite each other." Check square.github.io/retrofit and "Header Manipulation"
    – Amio.io
    Jun 28, 2014 at 7:41
38

The accepted answer is for an older version of Retrofit. For future viewers the way to do this with Retrofit 2.0 is using a custom OkHttp client:

OkHttpClient httpClient = new OkHttpClient.Builder()
  .addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
      Builder ongoing = chain.request().newBuilder();
      ongoing.addHeader("Accept", "application/json;versions=1");
      if (isUserLoggedIn()) {
        ongoing.addHeader("Authorization", getToken());
      }
      return chain.proceed(ongoing.build());
    }
  })
  .build();

Retrofit retrofit = new Retrofit.Builder()
  // ... extra config
  .client(httpClient)
  .build();

Hope it helps someone. :)

16
  • 5
    In common usage with dagger2, retrofit2 will be singleton, therefore httpclient wont be created each time. in that case isUserLoggedIn() does not make sense, am i right? Only solution i can see currently is to force retrofit2 reinitialization when user login status is changed, so that appropriate header gets added or removed from request.. or there is some obvious solution that i cant see currently ? Thanks.
    – bajicdusko
    May 7, 2016 at 15:06
  • 2
    @bajicdusko this is my exact same connundrum. Have you found a solution? It seems so wasteful, and strange that the previous version was more efficient.
    – deed02392
    Jun 12, 2016 at 20:11
  • @deed02392 You can set a composite Interceptor to which you can set or reset the interceptor at a later stage. However, I would argue that having retrofit as a singleton may a sign of early optimisation. There is no overhead on creating a new retrofit instance: github.com/square/retrofit/blob/master/retrofit/src/main/java/…
    – pablisco
    Jun 12, 2016 at 20:48
  • I did not really think about it deeply. I have some ApiFactory class which is also initialized with dagger2, and it is responsible for initialization of retrofit. I have exposed one public method in ApiFactory which forces reinitialization of retrofit instance when needed, so its quite simple. I might doing it wrong, but it did the job, and i am using it only for Authorization header so its used when user login or logout. Another option is to use @Header annotation inside endpoint definition, which was not acceptable for me. I should set it on each endpoint which is not practical.
    – bajicdusko
    Jun 12, 2016 at 20:49
  • @pablisco Ah from my understanding you couldn't add or remove Interceptors once you'd created a Retrofit2 instance.
    – deed02392
    Jun 12, 2016 at 21:11
8

Retrofit 2.3.0

OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    okHttpClientBuilder
            .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Request.Builder newRequest = request.newBuilder().header("Authorization", accessToken);
                    return chain.proceed(newRequest.build());
                }
            });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(GithubService.BASE_URL)
            .client(okHttpClientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

I am using this to connect to GitHub.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.