【发布时间】:2022-09-23 07:18:23
【问题描述】:
我正在尝试将全局标头与 headerInterceptor 一起使用,但是当我对其进行测试时,它们似乎无法正常工作。当我在 apiService 中使用 @Headers(\"Content-Type: application/json\") 时,它可以工作。 我遵循了几个教程,但在代码中找不到任何差异。
fun getRetrofit(): Retrofit{
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private val client = OkHttpClient.Builder()
.addInterceptor(HeaderInterceptor())
.build()
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
.newBuilder()
.addHeader(\"Content-Type\", \"application/json\")//This doesn\'t work
.build()
return chain.proceed(request)
}
}
我在协程中这样调用 getRetrofit() :
val respuesta = getRetrofit().create(KiritoApiService::class.java).requestMyToken(salida).execute()
我正在使用的相关依赖项是:
implementation \"com.squareup.retrofit2:retrofit:2.9.0\"
implementation \"com.squareup.retrofit2:converter-gson:2.9.0\"
implementation \"com.squareup.okhttp3:logging-interceptor:4.5.0\"
我也尝试将 .addHeader() 更改为 .header() ,但没有成功。 我已经在@POST 请求中使用了@Headers() 标签,但我希望它能够工作,因为它更具可读性并且我可以少犯错误。提前谢谢了!!