我正在为我的Android应用程序使用MVP
模式,我需要向我的请求标头中添加访问令牌。访问令牌保存在SharedPreferences
中。如何以SharedPreferences
模式访问该MVP
。我正在使用Retrofit
进行网络请求。
public class RetrofitInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "http://123124.ngrok.io/api/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
okhttpBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().addHeader("Authorization", "Bearer "); //need to add value from SharedPreferences
return chain.proceed(newRequest.build());
}
});
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
答案 0 :(得分:1)
尝试:
private static Retrofit authRetrofit = null;
public static Retrofit getAuthClient(Context context) {
if (authRetrofit == null) {
final AuthSharedPref authSharedPref = new AuthSharedPref(context);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer "+authSharedPref.getToken()).build();
return chain.proceed(request);
}
});
authRetrofit= new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return authRetrofit;
}
在这里,AuthSharedPref是一个共享首选项类,用于存储登录详细信息,您可以将其更改为自己的登录详细信息。
答案 1 :(得分:1)
您可以使用应用程序Context
尝试这种方式
public class RetrofitInstance {
private static Retrofit retrofit;
private Context context;
private static final String BASE_URL = "http://123124.ngrok.io/api/";
public void init(Context context) {
this.context = context;
}
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
okhttpBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//use context
Request.Builder newRequest = request.newBuilder().addHeader("Authorization", "Bearer "); //need to add value from SharedPreferences
return chain.proceed(newRequest.build());
}
});
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
和在应用程序类中
public class YourApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RetrofitInstance.getRetrofitInstance().init(getApplicationContext());
}
}