Retrofit 2 - URL Query Parameter

Alan picture Alan · Apr 19, 2016 · Viewed 104.3k times · Source

I am using a query parameters to set the values needed by the Google Maps API.

The issue is I do not need the & sign for the first query parameter.

@GET("/maps/api/geocode/json?")
    Call<JsonObject> getLocationInfo(@Query("address") String zipCode,
                                             @Query("sensor") boolean sensor,
                                             @Query("client") String client,
                                             @Query("signature") String signature);

Retrofit generates:

&address=90210&sensor=false&client=gme-client&signature=signkey

which causes the call the fail when I need it to be

address=90210&sensor=false&client=gme-client&signature=signkey

How do I fix this?

Answer

Andreas picture Andreas · Apr 20, 2016

If you specify @GET("foobar?a=5"), then any @Query("b") must be appended using &, producing something like foobar?a=5&b=7.

If you specify @GET("foobar"), then the first @Query must be appended using ?, producing something like foobar?b=7.

That's how Retrofit works.

When you specify @GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.

Remove the ?, and you will get the desired result.