How to add Api_KEY into interceptor using okhttp

2020-07-16 12:27发布

问题:

I have this service where I want to put the token as an interception in the okhttp instead of passing as a parameter with @Header("MY_API_KEY")

This is my code regarding the service

/**
     * 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)
    }

How can I add an interceptor for header authorization in here?

回答1:

add like this

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();

in kotlin its like

 val logging = HttpLoggingInterceptor()
    logging.level = HttpLoggingInterceptor.Level.BODY

    val httpClient = OkHttpClient.Builder()
    httpClient.addInterceptor { chain ->
        val original = chain.request()

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

        val request = requestBuilder.build()
        chain.proceed(request)
    }


    httpClient.connectTimeout(30, TimeUnit.SECONDS)
    httpClient.readTimeout(30, TimeUnit.SECONDS)

    httpClient.addNetworkInterceptor(logging)

 val okHttpClient=httpClient.build()