android 空对象引用上的共享首选项

drkbr07n  于 2022-12-21  发布在  Android
关注(0)|答案(1)|浏览(181)

TokenInterceptor.class

public OkHttpClient getClients(Context context) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    SharedPreferences preferences = context.getSharedPreferences("logged", MODE_PRIVATE);
    String tokens = preferences.getString("token", "");
    return new OkHttpClient
                .Builder()
                .addInterceptor(interceptor)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        Request request = chain.request().newBuilder()
                                .header("Accept", "application/json")
                                .header("xc-auth", ""+tokens)
                                .build();

                        return chain.proceed(request);

                    }
                })
                .readTimeout(90, TimeUnit.SECONDS)
                .writeTimeout(90, TimeUnit.SECONDS)
                .connectTimeout(90, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .cache(null)
                .build();
    }

ApiClient.class

public static Retrofit getClient() {
    OkHttpClient client = new TokenInterceptor().getClients();
    if (retrofit == null) {
        Gson gson = new GsonBuilder().setLenient()
                                     .create();
        retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))

                    .build();
    }
    return retrofit;
}

MainActivity.class
一个二个一个一个

7lrncoxx

7lrncoxx1#

更改为ApiClient.java,如下所示:

public static Retrofit getClient(Context context) {
    OkHttpClient client = new TokenInterceptor().getClients(context);
    ...
}

转换为MainActivity.java,如下所示:

new ApiClient().getClient(MainActivity.this);

相关问题