有选择地将不记名令牌添加到改造中的标头 [英] Add bearer token selectively to header in Retrofit

查看:44
本文介绍了有选择地将不记名令牌添加到改造中的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何选项可以根据 Retrofit 中的标志或注释启用/禁用标头拦截器.由于我的 API 中很少有不需要令牌的路径,因此我需要跳过向这些 API 调用添加令牌的步骤.

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

推荐答案

我前段时间研究过这个问题,我没有找到任何开箱即用的改造提供的解决方案,但您可以轻松地自己实现一个解决方法.

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.

只需使用您选择的标头对请求进行注释,例如NoAuth: true"并在拦截器中检查此标头:

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

这篇关于有选择地将不记名令牌添加到改造中的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆