我有一个与REST API通信的Android应用程序.
对于每个请求,我希望我的应用程序除了必需参数外还能够添加可选参数.
如何使用Retrofit实现此功能?目前,所有参数都在接口中进行了硬编码:
@GET("/user/{id}/comments?position={pos}") void getComments(@Path("id") int id, @Query("pos") int pos, Callbackcb); @GET("/user/{id}/likes?n={number}") void getLikes(@Path("id") int id, @Query("number") int number, Callback cb); /* etc */
是否可以"子类" RestAdapter
或能够动态地向我的请求添加可选参数的东西?
您有几种方法可以实现这一目标:
默认情况下,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) } } });
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);