我正在尝试通过改造和 rxjava2 以编程方式向我的 api 调用添加授权 header ,因此我向其添加了一个 okhttp3 拦截器。这是我的完整代码:
public interface APIService {
class ServiceInterceptor implements Interceptor{
@NonNull
@Override
public okhttp3.Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
if (request.header("No-Authentication") == null){
SharedPreferences sharedPref = ???.getSharedPreferences(USER, Context.MODE_PRIVATE); <---
request = request.newBuilder()
.addHeader("Authorization", "JWT " + sharedPref.getString("auth_token", null))
.build();
}
return chain.proceed(request);
}
}
OkHttpClient apiClient = new OkHttpClient().newBuilder()
.addInterceptor(new ServiceInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.8:8000/api/v1/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(apiClient)
.build();
@GET("rest-auth/user/")
Single<Response<User>> getUserDetails();
@POST("rest-auth/login/")
@Headers("No-Authorization: true")
Single<Response<AuthUserResponse>> loginUser(@Body LoginRequest body);
@POST("rest-auth/registration/")
@Headers("No-Authorization: true")
Single<Response<AuthUserResponse>> signupUser(@Body SignupRequest body);
}
问题是我无法从 sharedPreferences 检索 auth_token,因为我不知道如何将上下文传递给它。有什么建议么? 谢谢。
最佳答案
您需要为您的 ServiceInterceptor
类创建一个构造函数,将 auth_token
作为参数传递,类似于
private String authToken;
public ServiceInterceptor(String authToken) {
this.authToken = authToken;
}
这样你就可以在拦截器类之外处理上下文和 SharedPreferences,无论如何它都不应该知道 android 的东西。
然后在您的intercept
方法中您可以获得authToken。
关于android - 在 retrofit2 界面中检索 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53504324/