Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit: multiple query parameters in @GET command?

I am using Retrofit and Robospice to make API calls in my android application. All @POST methods work great, and so do @GET commands without any parameters in the URL, but I can't get any @GET calls to work with parameters on the end!

For example, if my API path was "my/api/call/" and I wanted 2 parameters "param1" and "param2" in the URL, the get call would look like:

http://www.example.com/my/api/call?param1=value1&param2=value2

so I have setup my @GET interface like so:

@GET("/my/api/call?param1={p1}&param2={p2}") Response getMyThing(@Path("p1") String param1, @Path("p2") String param2); 

but I get an error saying
"An exception occurred during request network execution : URL query string "/my/api/call?param1={p1}&param2={p2}" on method getMyThing may not have replaced block."

What am I doing wrong?

like image 318
AndroidNoob Avatar asked Nov 14 '13 10:11

AndroidNoob


People also ask

What is @query in retrofit?

Query Parameters with RetrofitRetrofit uses annotations to define query parameters for requests. The annotation is defined before method parameters and specifies the request parameter name. The desired value for this parameter is passed during method call.


2 Answers

You should be using this syntax:

@GET("/my/API/call") Response getMyThing(     @Query("param1") String param1,     @Query("param2") String param2); 

Specifying query parameters in the URL is only for when you know both the key and value and they are fixed.

like image 98
Jake Wharton Avatar answered Oct 11 '22 04:10

Jake Wharton


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>, 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("foo", "bar");        params.put("baz", "qux");        // ... 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/?foo=bar&baz=qux

like image 41
Julio Betta Avatar answered Oct 11 '22 04:10

Julio Betta