如何使用okhttp将Api_KEY添加到拦截器中 [英] How to add Api_KEY into interceptor using okhttp

查看:201
本文介绍了如何使用okhttp将Api_KEY添加到拦截器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

这是我关于服务的代码

/**
     * 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?

推荐答案

添加为这样

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

在kotlin中像

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

这篇关于如何使用okhttp将Api_KEY添加到拦截器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆