Java – How to configure Square’s Retrofit Client to handle requests with a variable number of parameters

How to configure Square’s Retrofit Client to handle requests with a variable number of parameters… here is a solution to the problem.

How to configure Square’s Retrofit Client to handle requests with a variable number of parameters

I’m building an Android app and using Square’s Retrofit library to make short network calls. I’m relatively new to Java and Android. So far I’ve constructed a request like this:

@GET("/library.php")
void library(
        @Query("one_thing") String oneThing,
        @Query("another_thing") String anotherThing,
        Callback<Map<String,Object>> callback
);

Then call them that:

    service.library(oneThing, anotherThing, callback);

I need to implement a request that accepts a variable number of parameters, no more than 10 or so. Having to define them separately and pass null or something else for those that don’t exist in a given request is cumbersome. Is there a way to define an interface for the request that accepts variable numbers or parameters and automatically constructs @Query for each element in the parameter dictionary/map? Like this:

@GET("/library.php")
void library(
        Map<String,Object> parameters,
        Callback<Map<String,Object>> callback
);

service.library(parameters, callback);

Thank you in advance for any tips.

EDIT: Passing null values for parameters that are not related to the request does not work in this case. Ideally, I would be able to set/create @Query based on the parameter dictionary so that if the value of the key is null, they don’t become @Query.

EDIT: I’m looking specifically for a solution for GET requests.

Solution

You can always try passing parameters as HTTP Bodies, e.g. this example (Note: I am the author).

But as you suggested, use map with your value instead, so this might work for you:

@POST("/library.php")
public void library(@Body Map<String, Object> parameters, Callback<Map<String,Object>> callback);

Related Problems and Solutions