如何使用okhttp将Api_KEY添加到拦截器中

时间:2018-08-14 00:05:29

标签: kotlin retrofit2 okhttp interceptor okhttp3

我有此服务,我想将令牌作为okhttp中的拦截放置,而不是通过@Header(“ MY_API_KEY”)作为参数传递

这是我关于服务的代码

/**
     * Provides the [PHService]
     */
    fun provideService(): PHService {

        val logger = HttpLoggingInterceptor()
        logger.level = HttpLoggingInterceptor.Level.BASIC



        val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()

        return Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(PHService::class.java)
    }

如何在此处添加用于头授权的拦截器?

1 个答案:

答案 0 :(得分:2)

这样添加

let x = 10;
let originalX = x;
x += originalX; // 20
x += originalX; // 30
x += originalX; // 40

在kotlin中像

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", "MY_API_KEY"); // <-- this is the important line

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });


    httpClient.connectTimeout(30, TimeUnit.SECONDS);
    httpClient.readTimeout(30, TimeUnit.SECONDS);
    httpClient.addNetworkInterceptor(logging);

 OkHttpClient client = httpClient.build();