我正在为我的Android应用程序使用MVP模式,我需要将访问令牌添加到我的请求头中。访问令牌保存在SharedPreferences中。如何在MVP模式中访问SharedPreferences。我正在使用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;
}
}
2条答案
按热度按时间hwazgwia1#
尝试:
在这里,AuthSharedPref是一个共享首选项类,用于存储登录详细信息,您可以将其更改为自己的登录详细信息。
6qftjkof2#
您可以使用应用程序
Context
试试这边
在Application类中