Retrofit2授权如何使用拦截器class获取访问令牌
Retrofit2 Authorization How to use Interceptor class for access token
我正在尝试在登录时获取令牌,然后在 Main Activity 中显示昵称。
但是 Main activity 中的昵称始终为空值。
我不确定如何从 Interceptor class 调用 Main Activity.
- 我想要的:
当前状态:
BasicAuthInterceptor class :
我尝试连接此 class 和主要 class。但它没有用。
(当我在main class中调试时,昵称值始终为null)
public class BasicAuthInterceptor implements Interceptor {
private String token;
public BasicAuthInterceptor(String token){
this.token = token;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
String token = UserPreference.getInstance().getString(Config.KEY_TOKEN);
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("authorization",token)
.build();
return chain.proceed(authenticatedRequest);
}
- 改装class
public class RetrofitClient {
public static RetrofitInterface buildHTTPClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("myurl")
.addConverterFactory(GsonConverterFactory.create())
.client(getClient())
.build();
return retrofit.create(RetrofitInterface.class);
}
private static OkHttpClient getClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(Config.KEY_TOKEN))
.build();
}
private static HttpLoggingInterceptor provideHttpLoggingInterceptor() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(@NotNull String message) {
Log.d("HTTP", message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return httpLoggingInterceptor;
}
public static RetrofitInterface getRestMethods() {
return buildHTTPClient();
}
- RetrofitInterface 接口:当我在 Main 中获取令牌时无法添加 Header 值 activity
public interface RetrofitInterface {
@FormUrlEncoded
@POST("v1/user/regist")
Call<UserRegisterData> regist(@Field("email") String email, @Field("nickname") String nickname, @Field("password") String password);
@FormUrlEncoded
@POST("v1/user/login")
Call<ApiResultDto> login(@Field("email") String email, @Field("password") String password);
// @Header("key : authorization","token")
@GET("v1/user/account")
Call<UserAccountData> account(@Header("authorization") String token);
}
- Main Activity : 登录后获取token和用户信息
public void initPreference() {
userPreference = new UserPreference();
userPreference.setContext(this);
}
public void userLogOut(View view) {
userPreference.setLoggedIn(getApplicationContext(), false);
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
@Override
public void onClick(View view) {
userLogOut(view);
}
private void getUser() {
getToken = userPreference.getString(Config.KEY_TOKEN);
RetrofitInterface retrofitInterface = RetrofitClient.getRestMethods();
Call<UserAccountData> call = retrofitInterface.account(getToken);
call.enqueue(new Callback<UserAccountData>() {
public void onResponse(Call<UserAccountData> call, Response<UserAccountData> response) {
if (response.isSuccessful()) {
String nickName =response.body().getNickname();
getNickName.setText(nickName);
Toast.makeText(getApplicationContext(), "token success", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UserAccountData> call, Throwable t) {
Toast.makeText(getApplication(), "token fail", Toast.LENGTH_SHORT).show();
}
});
}
您需要将它添加到 okhttp 客户端
private static OkHttpClient getClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
---> .addInterceptor(BasicAuthInterceptor("YOUR TOKEN"))
.build();
}
我正在尝试在登录时获取令牌,然后在 Main Activity 中显示昵称。 但是 Main activity 中的昵称始终为空值。 我不确定如何从 Interceptor class 调用 Main Activity.
- 我想要的:
当前状态:
BasicAuthInterceptor class : 我尝试连接此 class 和主要 class。但它没有用。 (当我在main class中调试时,昵称值始终为null)
public class BasicAuthInterceptor implements Interceptor {
private String token;
public BasicAuthInterceptor(String token){
this.token = token;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
String token = UserPreference.getInstance().getString(Config.KEY_TOKEN);
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("authorization",token)
.build();
return chain.proceed(authenticatedRequest);
}
- 改装class
public class RetrofitClient {
public static RetrofitInterface buildHTTPClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("myurl")
.addConverterFactory(GsonConverterFactory.create())
.client(getClient())
.build();
return retrofit.create(RetrofitInterface.class);
}
private static OkHttpClient getClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(Config.KEY_TOKEN))
.build();
}
private static HttpLoggingInterceptor provideHttpLoggingInterceptor() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(@NotNull String message) {
Log.d("HTTP", message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return httpLoggingInterceptor;
}
public static RetrofitInterface getRestMethods() {
return buildHTTPClient();
}
- RetrofitInterface 接口:当我在 Main 中获取令牌时无法添加 Header 值 activity
public interface RetrofitInterface {
@FormUrlEncoded
@POST("v1/user/regist")
Call<UserRegisterData> regist(@Field("email") String email, @Field("nickname") String nickname, @Field("password") String password);
@FormUrlEncoded
@POST("v1/user/login")
Call<ApiResultDto> login(@Field("email") String email, @Field("password") String password);
// @Header("key : authorization","token")
@GET("v1/user/account")
Call<UserAccountData> account(@Header("authorization") String token);
}
- Main Activity : 登录后获取token和用户信息
public void initPreference() {
userPreference = new UserPreference();
userPreference.setContext(this);
}
public void userLogOut(View view) {
userPreference.setLoggedIn(getApplicationContext(), false);
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
@Override
public void onClick(View view) {
userLogOut(view);
}
private void getUser() {
getToken = userPreference.getString(Config.KEY_TOKEN);
RetrofitInterface retrofitInterface = RetrofitClient.getRestMethods();
Call<UserAccountData> call = retrofitInterface.account(getToken);
call.enqueue(new Callback<UserAccountData>() {
public void onResponse(Call<UserAccountData> call, Response<UserAccountData> response) {
if (response.isSuccessful()) {
String nickName =response.body().getNickname();
getNickName.setText(nickName);
Toast.makeText(getApplicationContext(), "token success", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UserAccountData> call, Throwable t) {
Toast.makeText(getApplication(), "token fail", Toast.LENGTH_SHORT).show();
}
});
}
您需要将它添加到 okhttp 客户端
private static OkHttpClient getClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
---> .addInterceptor(BasicAuthInterceptor("YOUR TOKEN"))
.build();
}