我正在尝试使用自定义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,这是
答案 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)