Android 在2接口中检索SharedReferences
我试图通过改型和rxjava2以编程方式向api调用添加授权头,所以我在其中添加了一个okhttp3拦截器。这是我的完整代码:Android 在2接口中检索SharedReferences,android,sharedpreferences,retrofit2,rx-java2,Android,Sharedpreferences,Retrofit2,Rx Java2,我试图通过改型和rxjava2以编程方式向api调用添加授权头,所以我在其中添加了一个okhttp3拦截器。这是我的完整代码: public interface APIService { class ServiceInterceptor implements Interceptor{ @NonNull @Override public okhttp3.Response intercept(@NonNull Chain chain) t
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);
}
公共接口服务{
类ServiceInterceptor实现拦截器{
@非空
@凌驾
公共okhttp3.响应截获(@NonNull Chain Chain)引发IOException{
Request=chain.Request();
if(request.header(“无身份验证”)==null){
SharedReferences SharedReferences=???.GetSharedReferences(USER,Context.MODE_PRIVATE);您需要为ServiceInterceptor
类创建一个构造函数,并将auth_令牌作为参数传递,例如
private String authToken;
public ServiceInterceptor(String authToken) {
this.authToken = authToken;
}
通过这种方式,您在拦截器类之外处理上下文和共享引用,它无论如何都不应该知道android的内容
然后在您的intercept
方法上,您可以获得authToken。在ServiceInterceptor
类中添加构造函数如何?已经尝试过了,但是我必须在中传递上下文
。addInterceptor(新ServiceInterceptor())
在public okhttp3.Response intercept(@NonNull Chain Chain,Context mContext)中再添加一个方法参数怎么样
?我无法在那里传递上下文,方法不会从其超类重写,我如何在接口中调用SharedReferences?你不应该这样做。该接口实际上只用于API方法。为HttpClient和翻新创建创建创建一个类,并将这两个类都保留在接口之外。因此,总共应该有3个类。拦截器class,改造实例类,API接口类。