改装拦截器未向URL添加查询参数

时间:2019-08-07 11:13:21

标签: android kotlin retrofit

我正在尝试使用自定义interceptor在URL中添加apikey,但是它没有在URL中添加参数,因此响应正文为空。

CustomInterceptor

class CustomInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        val url = chain.request().url().newBuilder()
            .addQueryParameter("apiKey", API_KEY)
            .build()

        val request = chain.request().newBuilder()
            .url(url)
            .build()

        return chain.proceed(request)
    }
}

客户

class Client {

    companion object {

        const val API_KEY = "123123"
        private const val apiUrl = "https://www.omdbapi.com/"

        fun <T> create(service: Class<T>): T {
            val client = OkHttpClient.Builder()
                .addInterceptor(CustomInterceptor())
                .build()

            return Retrofit.Builder()
                .baseUrl(apiUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()
                .create(service)
        }
    }
}

IMovie

interface IMovie {

    @GET("/")
    fun searchMovie(@Query("s") query: String): Call<SearchResult>
}

发送请求后,响应正文为null,这是

实际网址:-https://www.omdbapi.com/?s=Man

预期的URL:-https://www.omdbapi.com/?s=Man&apikey=123123

1 个答案:

答案 0 :(得分:0)

首先从现有请求中创建一个新的httpUrl实例,并添加您的查询参数和值:

var request = chain.request()

val httpUrl = request.url().newBuilder().addQueryParameter("token", authToken).build()

然后更新请求:

request = request.newBuilder().url(httpUrl).build()

然后继续:

return chain.proceed(request)

  • 当您从链中调用该请求(在处理后继续执行该请求)时,您将再次收到未修改的请求。