2017-04-07 45 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

相關問題