Retrofit2授权如何将Interceptor类用于访问令牌

时间:2020-06-03 11:39:21

标签: android sharedpreferences retrofit2

我正在尝试在登录时获取令牌,然后在“主要活动”中显示一个昵称。 但是Main活动中的昵称始终为空值。 我不确定如何从Interceptor类调用Main Activity。

  • 我想做什么:
    enter image description here
  • 当前状态:
    enter image description here

  • BasicAuthInterceptor类: 我尝试将此类与主要课程联系起来。但这没有用。 (当我在主类中进行调试时,昵称值始终为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);
    }
  • 改装类
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接口:在主要活动中获得令牌时,我无法添加标头值
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);
}
  • 主要活动:登录后获取令牌和用户信息
 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();
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

您需要将其添加到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();
    }