Add bearer token selectively to header in Retrofit

笑着哭i 提交于 2019-12-11 07:35:51

问题


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


来源:https://stackoverflow.com/questions/41032720/add-bearer-token-selectively-to-header-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!