在Authenticator中设置SharedPreference?

时间:2017-05-05 01:14:00

标签: android retrofit retrofit2 okhttp okhttp3

我正在使用Android。我使用SharedPreferences存储我的身份验证令牌。

为了刷新auth令牌,我使用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);
    }

}

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点

我建议您创建一个Application类并在app中创建一个方法 称之为 getContext(),然后可以从任何地方访问该方法

你可以获得像 App.getContext()

这样的上下文

实施例

insert_one()

您可以像这样制作单身共享偏好

https://github.com/BioGram/Android/blob/master/app/src/main/java/co/biogram/main/handler/SharedHandler.java

答案 1 :(得分:1)

再添加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;
}