我需要向Retrofit 2.0.0-beta2库发出的每个请求添加查询参数。我为Retrofit 1.9找到了this solution,但是如何在最新的库版本中添加RequestInterceptor
?
我的界面:
@GET("user/{id}")
Call<User> getUser(@Path("id")long id);
@GET("users/")
Call<List<User>> getUser();
客户:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(CLIENT) // custom OkHTTP Client
.build();
service = retrofit.create(userService.class);
最佳答案
为了完整起见,这是您需要使用OkHttp-Interceptor向每个Retrofit 2.x请求添加参数的完整代码:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url().newBuilder().addQueryParameter("name","value").build();
request = request.newBuilder().url(url).build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("...")
.client(client)
.build();