使用当前代码向 Kotlin okHttp Retrofit2 中的每个请求添加自定义标头

问题描述 投票:0回答:2

我尝试通过将 .addHeader() 添加到 OkHttpClient.Builder() 来向每个请求添加自定义标头,但在构建时出现以下错误:

MicroApiClient.kt:(16, 14):未解析的参考:addHeader

如何使用下面的代码正确地将自定义标头添加到每个请求?

    package com.app.name.data
    
    import com.app.name.BuildConfig
    import com.app.name.data.source.remote.APPService
    import okhttp3.OkHttpClient
    import okhttp3.logging.HttpLoggingInterceptor
    import retrofit2.Retrofit
    import retrofit2.converter.gson.GsonConverterFactory
    import retrofit2.converter.scalars.ScalarsConverterFactory
    
    object MicroApiClient {
        private val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        private val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                // Attempting to add headers to every request
                .addHeader("x-api-key", BuildConfig.AWS_MICROSERVICES_API_KEY)
                .build()
        val instance: APPService by lazy {
            val retrofit = Retrofit.Builder()
                    .baseUrl(BuildConfig.AWS_MICROSERVICES_HOST)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .client(okHttpClient)
                    .build()
    
            retrofit.create(APPService::class.java)
        }
    }
android-studio kotlin retrofit2 okhttp
2个回答
4
投票

根据Retrofit文档:

拦截器可以添加、删除或替换请求标头。

拦截器用于操纵传出请求或传入响应。在您的情况下,您必须将 API_KEY 添加到每个请求作为标头。这就是拦截器可以派上用场的地方。您可以在拦截器中添加标头,如下所示:

 private val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                // Attempting to add headers to every request
                .addInterceptor { chain ->
                     val request = chain.request().newBuilder()
                     .addHeader("x-api-key", BuildConfig.AWS_MICROSERVICES_API_KEY)
                     chain.proceed(request.build())
                }
                .build()

0
投票

很简单;只使用addHeader方法。例如:

var request= Request.Builder()
                .addHeader("Token","test")
                .addHeader("UserName","test user")
                .url(url)
                .post(jsonBody)
                .build()
© www.soinside.com 2019 - 2024. All rights reserved.