2017-04-07 39 views
0

我使用了大量的Retrofit调用(GET,PUT,DETELE等)。我知道,我可以为所有电话进行此操作,但我必须将其设置为GET电话。但是现在我必须为所有的GET调用添加一个静态参数,最好的方法是什么?如何将静态参数添加到选定的GET Retrofit调用?

我的电话的例子:

@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); 

我需要的一切又增添parametr: &东西=真

我想补充的是这种方式,但这需要解决所有呼叫接口:

public interface ApiService { 

    String getParameterVariable = "something" 
    boolean getParameterValue = true 

    @GET("user") 
    Call<User> getUser(@Header("Authorization") String authorization, 
         @Query(getParameterVariable) Boolean getParameterValue) 

} 

回答

3

这个答案假设你正在使用OkHttp以及Retrofit

您必须为您的OkHttpClient实例添加一个拦截器,该实例可以过滤所有GET请求并应用查询参数。 你可以这样做:

// 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); 
    } 
}); 
+0

好男人,谢谢你! – Michalsx

相关问题