Modernization: several request parameters in the @GET command?

I use Retrofit and Robospice to make API calls in my Android app. All @POST methods work just fine, like @GET commands with no parameters in the URL, but I can't get any @GET calls to work with parameters at the end!

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

http://www.example.com/my/api/call?param1=value1¶m2=value2

so I configured my @GET interface like this:

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

but i get an error
"An exception occurred while executing a network request: the URL request line" /my/api/call?param1={p1}¶m2={p2} "for the getMyThing method may not have replaced the block."

What am I doing wrong?

+47
android api get retrofit robospice
Nov 14 '13 at 10:19
source share
4 answers

You should use this syntax:

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

Setting request parameters in the URL is performed only when you know both the key and value, and they are fixed.

+107
Nov 14 '13 at 10:27
source share

If you have a set of GET parameters, another way to pass them to your URL is with 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 will be http://www.example.com/thing/?foo=bar&baz=qux

+12
Nov 11 '14 at 15:17
source share

Do not write your request parameters in the GET URL. Do it like this:

 @GET("/my/api/call") Response getMyThing(@Query("param1") String param1, @Query("param2") String param2); 
+6
Nov 14 '13 at 10:30
source share

You can create a parameter map and send it as shown 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
Dec 14 '18 at 6:22
source share



All Articles