在我的 Android kotlin 应用程序中,我使用 Retrofit2 调用一些 api,例如
@FormUrlEncoded
@POST("something/some")
fun callMyApi(
@Field("myField") myField: String
): Deferred<MyResponseClass>
现在我需要向所有 api 请求添加一些常见的 post 参数(并保留每个调用的特定参数,在本例中我需要保留“myField”),因此我使用拦截器:
val requestInterceptor = Interceptor { chain ->
val newRequest = chain.request()
.newBuilder()
.post(
FormBody.Builder()
.add("common1Key", "common1")
.add("common2Key", "common2")
.add("common3Key", "common3")
.build()
)
.build()
return@Interceptor chain.proceed(newRequest)
}
但是这个实现失败了,因为拦截器似乎覆盖了myField。 我该如何修复它?
最佳答案
我们可以使用两个或多个通用查询参数来创建拦截器。
val requestInterceptor = Interceptor { chain ->
val url = chain.request()
.url()
.newBuilder()
.addQueryParameter("common1key", "common1")
.addQueryParameter("common2key", "common2")
.addQueryParameter("common3key", "common3")
.build()
val request = chain.request()
.newBuilder()
.url(url)
.build()
return@Interceptor chain.proceed(request)
}
关于android - Retrofit2:将post参数添加到拦截器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54981684/