我很困惑,我已经将令牌保存在SharedPrefernce中,并且当我尝试获取用户名时,即使我已经使用Header和Sharedpref令牌,我仍然无法将对象首选项设置为空。也许我的错误是没有给Header进行改造。在这里,我很困惑地添加标题。我使用了现有的参考,但是没有用。如果没有办法,我真的希望您能帮助我。

RetrofitClient.java

public class RetrofitClient {

        SharedPrefManager sharedPrefManager;
        private static Retrofit retrofit = null;

        public static Retrofit getClient(String baseUrl){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                                        .addInterceptor(interceptor)
                                        .build();

            if (retrofit == null){
                retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build();
            }
            return retrofit;
        }
    }


此令牌保存

SharedPrefManager sharedPrefManager;
sharedPrefManager.getSPToken()

最佳答案

这是样例改造客户

 public class RetrofitClient {


        private static Retrofit retrofit = null;

        public static Retrofit getClient(String baseUrl){
            HeaderInterceptor interceptor = new HeaderInterceptor();
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .build();

            if (retrofit == null){
                retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build();
            }
            return retrofit;
        }
    }


您的用例的拦截器。

public class HeaderInterceptor implements Interceptor {

    SharedPrefManager sharedPrefManager = new SharedPrefManager();

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request originalRequest = chain.request();

        Request newRequest = originalRequest.newBuilder()
                .header("Language", sharedPrefManager.getSPToken())
                .build();

        return chain.proceed(newRequest);

    }
}

08-26 14:15