【问题标题】:I can't use addHeader() in an interceptor with retrofit我不能在改装的拦截器中使用 addHeader()
【发布时间】: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() 标签,但我希望它能够工作,因为它更具可读性并且我可以少犯错误。提前谢谢了!!

    标签: android kotlin retrofit


    【解决方案1】:

    你怎么知道它不起作用?你的代码看起来是合法的,但毕竟可能有一些隐藏的陷阱。

    为了缩小问题范围,我建议另外添加一个日志拦截器(你已经有了依赖):

    private val client = OkHttpClient.Builder()
        .addInterceptor(HeaderInterceptor())
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .build()
    

    我在我的机器上复制了您的代码,并且日志记录显示标头已按应有的方式设置:

    I/okhttp.OkHttpClient: Content-Type: application/json
    

    这表明问题可能与标题无关。您的请求可能还有其他问题。正如我所说,请如上所述添加记录器拦截器。也许您可以在此处共享此输出以进行进一步调试。

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2015-11-22
      • 2015-10-04
      • 1970-01-01
      • 2013-06-25
      • 2018-08-09
      相关资源
      最近更新 更多