Android Studio 使用当前代码在KotlinokHttp retrofit2中为每个请求添加自定义头

new9mtju  于 2023-10-23  发布在  Android
关注(0)|答案(2)|浏览(210)

我试图通过添加.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)
        }
    }
z9ju0rcb

z9ju0rcb1#

根据改装文件:
拦截器可以添加、删除或替换请求头。
拦截器用于操纵传出的请求或传入的响应。在您的情况下,您必须将 API_KEY 作为Header添加到每个请求。拦截器就在那里派上用场了。您可以在拦截器中添加header,如下所示:

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

uoifb46i2#

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

var request= Request.Builder()
                .addHeader("Token","test")
                .addHeader("UserName","test user")
                .url(url)
                .post(jsonBody)
                .build()

相关问题