我是android开发新手,我正在开发简单的移动应用程序,我使用Retrofit调用登录服务。一旦我从登录服务获得响应( token ),我应该如何在 OkHttp 拦截器中存储和使用该 token 。
提前致谢。
API客户端
package com.example.dell01.firstapplication.service;
import com.example.dell01.firstapplication.UserSession;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class APIClient {
public static final String BASE_URL = "actual url";
public static Retrofit retrofit = null;
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder().header("Token", "token here");
Request newRequest = builder.build();
return chain.proceed(newRequest);
}
}).build();
public static Retrofit getAPIClient(){
if(retrofit == null){
retrofit = new Retrofit
.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
API接口(interface)
package com.example.dell01.firstapplication.service;
import com.example.dell01.firstapplication.model.Token;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface APIInterface {
@POST("user/authenticate")
@FormUrlEncoded
Call<Token> getToken(@Field("username") String username, @Field("password") String password);
}
最佳答案
您可以使用SharedPreferences
这里是完整的文档: SharedPreferences
示例:
保存:
SharedPreferences preferences = getSharedPreferences("myPrefs", MODE_PRIVATE);
preferences.edit().putString("token", hawkerauthToken).commit();
检索:
String token = preferences.getString("token","");
关于android - 如何在Android中存储 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264428/