Add bearer token selectively to header in Retrofit

2019-07-31 07:55发布

问题:

I would like to know if there is any option to enable/disable header Interceptor based on a flag or annotation in Retrofit. Since there are few paths in my API that do not need a token, I need to skip adding token to those API calls.

Currently I have a simple Interceptor which will add a header to all the requests that are made from my application

//builder is of type OkHttpClient.Builder
builder.addInterceptor(chain -> {
    Request request = chain.request().newBuilder().
    addHeader("authorization", "Bearer foofootoken").build();

    return chain.proceed(request);
});

回答1:

I have researched this some time ago and I didn't find any solution provided by retrofit out of the box, but you can easily implement a workaround by yourself.

Just annotate the request with a header of your choosing, for example "NoAuth: true" and check for this header in the interceptor:

builder.addInterceptor(chain -> {
    String noAuthHeader = chain.request().header("NoAuth");
    Request.Builder request = chain.request().newBuilder();
    if(noAuthHeader == null || !noAuthHeader.equals("true")){
        request.addHeader("authorization", "Bearer foofootoken").build();
    }

    return chain.proceed(request.build());
});