android – Dynamically add optional parameters to API requests-ThrowExceptions

Exception or error:

I have an Android app that communicates with a REST API.

For each request, I want my app to be able to add optional parameters in addition to the mandatory parameters.

How can I implement this with Retrofit? Currently all the parameters are hard-coded in the interface:

@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 */

Is it possible to “sub-class” the RestAdapter or something to be able to dynamically add optional parameters to my requests?

How to solve:

You have a few ways to achieve that:

  • By default Retrofit handles nulls correctly for all null query parameters, so you can do something like:

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

If you use Object instead of int you can call to the method using null for the optional parameters:

    getLikes(1, null, null, cb); // to get /user/1/likes
    getLikes(1, 2, null, cb); // to get /user/1/likes?n=2
  • By using 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)
                    }                      
                }
            });
    

###

Support for Map<String,String> is now available. Just use @QueryMap Map<String, String> params.

From http://square.github.io/retrofit/:

For complex query parameter combinations a Map can be used.

Example:

@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

Leave a Reply

Your email address will not be published. Required fields are marked *