Search code examples
androidretrofitretrofit2okhttpgiphy-api

Pass multiple values to single parameter retrofit2


I'm trying to pass multiple Values to a SINGLE parameter for example :

http://api.giphy.com/v1/gifs?api_key=dc6zaTOxFJmzC&ids=feqkVgjJpYtjy,7rzbxdu0ZEXLy

I tried the following :

 @GET("gifs")
    Call<GIFModelMain> getGifsByID(@Field("ids")ArrayList<String> values, @Query("api_key") String API_KEY);

In my activity :

ArrayList<String> x = new ArrayList<>();
        x.add("feqkVgjJpYtjy");
        x.add("7rzbxdu0ZEXLy");
        gifCall = interf.getGifsByID(x, BuildConfig.GIPHY_API_TOKEN);

But the built URL is of form:

http://api.giphy.com/v1/gifsids=feqkVgjJpYtjy&ids=7rzbxdu0ZEXLy&api_key=API_KEY_BLANK

I looked up similar questions but found no correct answer.

EDIT: As per what TooManyEduardos said i changed my Interface to

@GET("gifs")
    Call<GIFModelMain> getGifsByID(@QueryMap Map<String, String> parameters,@Query("api_key") String API_KEY);

And my activity is now :

Map<String,String> map = new HashMap<>();
        map.put("ids","feqkVgjJpYtjy");
        map.put("ids","7rzbxdu0ZEXLy");

        gifCall = interf.getGifsByID(map, BuildConfig.GIPHY_API_TOKEN);

But the built URL is still : 03-30 02:46:23.922: E/FavActivity(21607): Url : api.giphy.com/v1/gifs?ids=7rzbxdu0ZEXLy&api_key=KEY_HERE


Solution

  • You're looking for a

    Map<String,String>
    

    And in your @Get interface, you'll receive it like this:

    (@QueryMap Map<String, String> parameters)
    

    So your whole interface call would be like this:

    @GET("gifs")
    Call<GIFModelMain> getGifsByID(@QueryMap Map<String, String> parameters);
    

    I wrote a whole tutorial on how to use Retrofit 2 if you want to check it out: http://toomanytutorials.blogspot.com/2016/03/network-calls-using-retrofit-20.html

    EDIT If you really want to pass multiple parameters, regardless of their key name, you can always do this:

    Call<GIFModelMain> getGifsByID(@Query("api_key") String API_KEY, @Query("ids") String id1, @Query("ids") String id2, @Query("ids") String id3);
    

    The obvious problem here is that you'll have to make multiple versions of the same method depending on how many ids you're passing