Retrofit2:将post参数添加到拦截器中

时间:2019-03-04 10:49:42

标签: android kotlin retrofit2 kotlin-android-extensions

在我的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 。 我该如何解决?

2 个答案:

答案 0 :(得分:1)

我们可以使用两个或多个常用查询参数来创建拦截器。

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)
        }

答案 1 :(得分:0)

我为表单主体添加了Interceptor。

interface PostWebApiService {  

@POST("posts")
@FormUrlEncoded
fun savePost(
    @Field("title") title: String
): Deferred<Post>

companion object {
    operator fun invoke(): PostWebApiService {
        val requestInterceptor = Interceptor { chain ->
            var request = chain.request()

            val requestBuilder = request.newBuilder()
            val formBody = FormBody.Builder()
                .add("body", "Body")
                .add("userId", "12")
                .build()
            var postBodyString = bodyToString(request.body())
            val concat = if (postBodyString.isNotEmpty()) "&" else ""
            postBodyString = postBodyString + concat + bodyToString(formBody)
            request = requestBuilder.post(
                RequestBody.create(
                    MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"),
                    postBodyString
                )
            )
                .build()
            return@Interceptor chain.proceed(request)
        }
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(requestInterceptor)
            .build()
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("http://jsonplaceholder.typicode.com/")
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(PostWebApiService::class.java)
    }

    fun bodyToString(request: RequestBody?): String {
        try {
            var buffer = Buffer()
            request?.writeTo(buffer)
            return buffer.readUtf8()
        } catch (e: IOException) {
            return "error"
        }
    }
}
}