Retrofit and GET using parameters Retrofit and GET using parameters android android

Retrofit and GET using parameters


AFAIK, {...} can only be used as a path, not inside a query-param. Try this instead:

public interface FooService {        @GET("/maps/api/geocode/json?sensor=false")    void getPositionByZip(@Query("address") String address, Callback<String> cb);}

If you have an unknown amount of parameters to pass, you can use do something like this:

public interface FooService {        @GET("/maps/api/geocode/json")    @FormUrlEncoded    void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);}


@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {private static final String BASEPATH = "http://www.example.com";private interface API {    @GET("/thing")    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);}public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.your_layout);   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();   API service = rest.create(API.class);   Map<String, String> params = new HashMap<String, String>();   params.put("key1", "val1");   params.put("key2", "val2");   // ... as much as you need.   service.getMyThing(params, new Callback<String>() {       // ... do some stuff here.   });}}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2


I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:

public interface LocationService {        @GET("/example/")    void getLocation(@Query(value="latlng", encoded=true) String latlng);}

Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:

String latlng = location.getLatitude() + "," + location.getLongitude();service.getLocation(latlng);