【发布时间】:2017-10-03 08:21:17
【问题描述】:
我使用的是安卓系统。我使用SharedPreferences 存储我的身份验证令牌。
为了刷新身份验证令牌,我使用了Authenticator 类。
现在,我需要能够在 SharedPreferences 中设置新的身份验证令牌,但是,为了做到这一点,SharedPreferences 需要一个上下文。
当我没有上下文时,如何从 Authenticator 类设置新的(刷新的)身份验证令牌?
这是我的 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);
}
}
【问题讨论】:
-
你在哪里创建
TokenAuthenticator的实例? -
@Code-Apprentice 添加了代码。
-
你在哪里调用 createService()?
-
@Code-Apprentice 每当我需要从我的服务器获取数据时,我的应用程序中都会出现。在我上面的代码中,它用于
TokenAuthenticator类。 -
"在我上面的代码中,它用于
TokenAuthenticator类。"我很迷惑。TokenAuthenticator在哪里使用ApiClient.createService()?我在您发布的代码中看不到这一点。从我看到的依赖关系是相反的。现在我们需要上一层楼。谁打电话给getService()?
标签: android retrofit retrofit2 okhttp okhttp3