22

我有一个与 REST API 通信的 Android 应用程序。

对于每个请求,我希望我的应用程序能够在强制参数之外添加可选参数。

如何使用 Retrofit 实现这一点?目前所有参数都硬编码在界面中:

@GET("/user/{id}/comments?position={pos}")  
void getComments(@Path("id") int id, @Query("pos") int pos, Callback<String> cb);

@GET("/user/{id}/likes?n={number}")  
void getLikes(@Path("id") int id, @Query("number") int number, Callback<String> cb);

/* etc */

是否有可能“子类”RestAdapter或能够动态地向我的请求添加可选参数的东西?

4

2 回答 2

44

您有几种方法可以实现这一目标:

  • 默认情况下,Retrofit 会正确处理所有空查询参数的空值,因此您可以执行以下操作:

    @GET("/user/{id}/likes")  
    void getLikes(@Path("id") int id, @Query("n") Integer number, @Query("pos") Integer pos Callback<String> cb);
    

如果您使用 Object 而不是 int ,则可以使用 null 作为可选参数调用该方法:

    getLikes(1, null, null, cb); // to get /user/1/likes
    getLikes(1, 2, null, cb); // to get /user/1/likes?n=2
  • 通过使用 RequestInterceptor:

    RestAdapter.Builder builder= new RestAdapter.Builder()
    .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Accept", "application/json;versions=1");
                    if(/*condition*/){
                       request.addQueryParam(arg0, arg1)
                    }                      
                }
            });
    
于 2013-12-10T11:26:42.480 回答
19

支持Map<String,String>现在可用。只需使用@QueryMap Map<String, String> params.

来自http://square.github.io/retrofit/

对于复杂的查询参数组合,可以使用 Map。

例子:

@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
于 2014-09-01T14:55:08.763 回答