Retrofit2拦截器,仅在特定方法中使用令牌

问题描述 投票:0回答:3

我想在qazxsw poi中使用qazxsw poi。我选择了qazxsw poi方式,因为几乎所有方法都需要authorization,除了我正在使用其他方法进一步使用令牌。

我的问题是:我怎样才能做到这一点?

我将访问令牌存储在Retrofit2中。我的第一个想法是:“我可以在我的interceptor类中检索它,并根据令牌是否为null或它有值创建合适的authorization实例”(有或没有添加SharedPreferences到它。

不幸的是,这并不容易,因为RetrofitClient需要获得偏好。

我不知道如何将它传递到Retrofit类或如何进入它内部。

这是我的.client()课程:

Context

我的RetrofitClient是我设置超时的先前方法。

我想创建这样的实例:

RetrofitClient

然后: public class RetrofitClient { public static final String BASE_URL = "http://localhost"; public static Retrofit retrofit = null; private RetrofitClient() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) //.client(getRequestHeader()) .build(); } /*OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request newRequest = chain.request().newBuilder() .addHeader("Authorization", "Bearer" + ) } })*/ public static synchronized Retrofit getInstance() { if (retrofit == null) { retrofit = new Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()).build(); } return retrofit; } public Api getApi() { return retrofit.create(Api.class); } } //获得令牌 getRequestHeader() //当我拿到令牌时 这是好方法吗?

android authorization retrofit2 interceptor okhttp3
3个回答
1
投票

您可以使用应用程序上线时可用的应用程序上下文。从您的app类获取它:

private RetrofitClient() {
            tokenService.token = null;
            tokenService.readToken(ApplicationContext.getInstance());


            if (tokenService.token == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            } else {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client) //I have interceptor here with access token
                        .build();
            }
        }

然后只需使用RetrofitClient.getInstance().create(Api.class).getToken()获取您需要的上下文。通过这种方法,您可以实现您之前的想法并获得RetrofitClient.getInstance().create(Api.class).someMethod()类中的SharedPreferences。

不要忘记将您的应用类添加到清单。

更新:您只创建一次改装实例,因此如果您在拥有令牌时创建它 - 您将始终使用它,而应用程序处于活动状态。我认为,良好的做法是检查拦截器中的令牌。像这样的东西:

public class MyApp extends Application {
    private static MyApp instance;
    @Override
    public void onCreate() {
    super.onCreate();
    instance = this;
    //other code
}
public static MyApp getInstance() {
    return instance;
}

另外,我不知道你的tokenService是如何工作的。但请记住,最好是始终检查令牌的共享首选项,如果您在注销时清除它。因为您的tokenService可能会保留令牌字符串,即使它已在共享首选项中清除。


0
投票

只需在RetrofitClient或其他情况下将SharedPreferences添加为构造函数参数即可


0
投票

你可以通过以下方式做到:

首先使用单例实例创建一个首选项类

喜好

MyApp.getInstance()

然后在你的RetrofitClient类中更改如下:

RetrofitClient

RetrofitClient
© www.soinside.com 2019 - 2024. All rights reserved.