I have an Android app that communicates with a REST API.
For each request, I want my app to be able to add optional parameters in addition to the mandatory parameters.
How can I implement this with Retrofit? Currently all the parameters are hard-coded in the interface:
@GET("/user/{id}/comments?position={pos}") void getComments(@Path("id") int id, @Query("pos") int pos, Callback<String> cb); @GET("/user/{id}/likes?n={number}") void getLikes(@Path("id") int id, @Query("number") int number, Callback<String> cb); /* etc */
Is it possible to "sub-class" the RestAdapter
or something to be able to dynamically add optional parameters to my requests?
You can then use @DefaultValue if you need it: @GET @Path("/job/{param1}/{param2}") public Response method(@PathParam("param1") String param1, @PathParam("param2") String param2, @QueryParam("optional1") String optional1, @QueryParam("optional2") @DefaultValue("default") String optional2) { ... }
Enter the same URL in the Postman text field; you will get the multiple parameters in the Params tab. Even you can write each of the parameters and send a request with multiple parameters.
To do http get request with parameters in Angular, we can make use of params options argument in HttpClient. get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.
A web form can't be used to send a request to a page that uses a mix of GET and POST. If you set the form's method to GET, all the parameters are in the query string. If you set the form's method to POST, all the parameters are in the request body.
You have a few ways to achieve that:
By default Retrofit handles nulls correctly for all null query parameters, so you can do something like:
@GET("/user/{id}/likes") void getLikes(@Path("id") int id, @Query("n") Integer number, @Query("pos") Integer pos Callback<String> cb);
If you use Object instead of int you can call to the method using null for the optional parameters:
getLikes(1, null, null, cb); // to get /user/1/likes getLikes(1, 2, null, cb); // to get /user/1/likes?n=2
By using RequestInterceptor:
RestAdapter.Builder builder= new RestAdapter.Builder() .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("Accept", "application/json;versions=1"); if(/*condition*/){ request.addQueryParam(arg0, arg1) } } });
Support for Map<String,String>
is now available. Just use @QueryMap Map<String, String> params
.
From http://square.github.io/retrofit/:
For complex query parameter combinations a Map can be used.
Example:
@GET("/group/{id}/users") List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With