3

I'm building an Android App and am using Square's Retrofit library for short-lived network calls. I'm relatively new to Java and Android. Until now I've constructed requests like so:

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

And called them like so:

    service.library(oneThing, anotherThing, callback);

I need to implement a request that accepts a variable number of parameters, not more than 10 or so. It's cumbersome to have to define them individually and pass null or something for the ones that aren't present for a given request. Is there a way to define an interface for a request such that it accepts a variable number or parameters and auto-constructs @Querys for each element in the parameter dictionary/map? Something like this:

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

service.library(parameters, callback);

Thanks in advance for any tips.

Edit: passing null for params that aren't pertinent to the request wont work in this case. Ideally I'd be able to set/create @Querys based on the parameter dictionary, so that keys wont become a @Query if their value is null.

Edit: I'm specifically looking for a solution that works with GET requests.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
Alfie Hanssen
  • 16,964
  • 12
  • 68
  • 74

2 Answers2

3

You could always try passing the parameters as a HTTP Body instead, such as in this example (note: I'm the author)

But as you suggest, use a Map with your values instead, so this might work for you:

@POST("/library.php")
public void library(@Body Map<String, Object> parameters, Callback<Map<String,Object>> callback);
Erich
  • 2,743
  • 1
  • 24
  • 28
3

It's a bit late but I'll post it anyway just in case someone found the same problem on Google.

They've introduced the Annotation @QueryMap

This annotation let you pass and object that implements Map class, is not as nice as Post requests that let's you pass an Object as parameter but it get the works done.

@GET("/library.php")
public void library(@QueryMap Map<String, Object> parameters, Callback<Map<String,Object>> callback);
DanielDiSu
  • 1,139
  • 1
  • 11
  • 10