20

I have request that set list of services that are turned on for user.

Request has following format:

https://myserver.com/setservices?param1=val1&param2=val2&service[10]&service[1000]&service[10000]

List of service parameters ("service[10]&service[1000]&service[10000]") is created dynamically and each parameter doesn't have value. Is it possible to achive this using Retrofit?

Yuriy
  • 1,466
  • 2
  • 14
  • 30

3 Answers3

44

From the retrofit documentation:

For complex query parameter combinations a Map can be used.

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

I guess this will make what you want to achieve.

WojciechKo
  • 1,511
  • 18
  • 35
  • @QueryMap doesn't allow to include query parameters without value. From documentation: "Values are URL encoded and null will not include the query parameter in the URL" – Yuriy Sep 30 '14 at 09:33
  • 1
    What about empty strings? – WojciechKo Sep 30 '14 at 17:10
  • It produces URL with equality symbols: https://myserver.com/setservices?service[100]=&service[10000]=&service[10]= But server understands it fine. – Yuriy Sep 30 '14 at 17:38
6

I found workaround how to do this.

@GET("/setservices{services_query}")
ServicesSetResponse setServices(@EncodedPath("services_query") String servicesQuery);

And then:

getService().setServices("?param1=val1&param2=val2" + "&services[10]&services[100000]&services[1000000]")
Yuriy
  • 1,466
  • 2
  • 14
  • 30
4

We can pass using the @QueryMap as below:

GET("/movies")
Call<List<Movies>> getMovies(
    @QueryMap Map<String, String> options
);

To build the parameters:

Map<String, String> data = new HashMap<>();
data.put("director", "Haresh");
data.put("page", String.valueOf(2));

It will generate the Url like:

http://your.api.url/movies?page=2&director=Haresh

H_H
  • 1,460
  • 2
  • 15
  • 30