Retrofit: multiple query parameters in @GET command?

后端 未结 4 1093
误落风尘
误落风尘 2020-12-23 09:30

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

相关标签:
4条回答
  • 2020-12-23 09:42

    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.

    0 讨论(0)
  • 2020-12-23 09:48

    Do not write your Query params in GET-URL. Do it like this:

    @GET("/my/api/call")
    Response getMyThing(@Query("param1") String param1,
                        @Query("param2") String param2);
    
    0 讨论(0)
  • 2020-12-23 09:56

    You can create a Map of params and send it like below:

    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put("p1", param1);
    paramsMap.put("p2", param2);
    
    // Inside call
    @GET("/my/api/call")
    Response getMyThing(@QueryMap Map<String, String> paramsMap);
    
    0 讨论(0)
  • 2020-12-23 10:02

    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

    0 讨论(0)
提交回复
热议问题