Reputation: 3621
I have use a lot of Retrofit calls (GET,PUT,DETELE,etc.). I know, I can do it for all calls, but I must set it only to GET calls. But now I have to add one static parametr to all GET calls, what is best way to do it?
My call examples:
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
I need for all GETs to add parametr: &something=true
I tried to add is this way, but this require to fix all calls to interface:
public interface ApiService {
String getParameterVariable = "something"
boolean getParameterValue = true
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization,
@Query(getParameterVariable) Boolean getParameterValue)
}
Upvotes: 1
Views: 559
Reputation: 16224
This answer assume that you are using OkHttp
together with Retrofit
.
You have to add an interceptor to your OkHttpClient
instance that filters all GET
requests and apply a query parameter.
You can do it in this way:
// Add a new Interceptor to the OkHttpClient instance.
okHttpClient.interceptors().add(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Check the method first.
if (request.method().equals("GET")) {
HttpUrl url = request.url()
.newBuilder()
// Add the query parameter for all GET requests.
.addQueryParameter("something", "true")
.build();
request = request.newBuilder()
.url(url)
.build();
}
// Proceed with chaining requests.
return chain.proceed(request);
}
});
Upvotes: 4