gpt4 book ai didi

android - 在 Authenticator 中设置 SharedPreference?

转载 作者:搜寻专家 更新时间:2023-11-01 09:35:18 29 4
gpt4 key购买 nike

我正在使用安卓系统。我使用 SharedPreferences 存储我的身份验证 token 。

为了刷新身份验证 token ,我使用了 Authenticator 类。

现在,我需要能够在 SharedPreferences 中设置新的身份验证 token ,但是,为了做到这一点,SharedPreferences 需要上下文。

当我没有上下文时,如何从 Authenticator 类设置新的(刷新的)授权 token ?

这是我的 Authenticator 类:

public class TokenAuthenticator implements Authenticator {
private String authToken;

public TokenAuthenticator(String authToken) {
this.authToken = authToken;
}

@Override
public Request authenticate(Route route, Response response) throws IOException {
if (responseCount(response) >= 3) {
return null;
}

ApiInterface apiService = ApiClient.createService(ApiInterface.class, authToken);
Call<BasicResponse> call = apiService.refreshAuthToken();
BasicResponse apiResponse = call.execute().body();

String newToken = apiResponse.getData().getToken();

// Set the new token in shared preferences (how to get context?)
SharedPreferences sp = getSharedPreferences(context);
sp.edit().putString("AUTH_TOKEN", token).apply();

return response.request().newBuilder()
.header("Authorization", "Bearer " + newToken)
.build();
}

private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}

}

这是调用 Authenticator 类的地方:

public class ApiClient {

public static final String API_URL = "http://www.user324211.com/";

private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();

private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create());

private static Retrofit retrofit = builder.build();

public static Retrofit getRetrofit() {
return retrofit;
}

public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}

public static <S> S createService(Class<S> serviceClass, final String authToken) {
if (authToken != null) {
TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(authToken);
httpClient.authenticator(tokenAuthenticator);
}

builder.client(httpClient.build());
retrofit = builder.build();

return retrofit.create(serviceClass);
}

}

最佳答案

再添加1个参数

public TokenAuthenticator(Context context,String authToken) {
this.authToken = authToken;
this.mContext = context;
}

用法

TokenAuthenticator tA = new TokenAuthenticator(this,YOUR_AUTH_TOKEN);

编辑

如果没有上下文调用,则只传递 SharedPreferences

public TokenAuthenticator(SharedPreferences shared,String authToken) {
this.authToken = authToken;
this.mShared = shared;
}

关于android - 在 Authenticator 中设置 SharedPreference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43794994/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com