Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit 2 @path Vs @query

I am new to retrofit 2 library.I read several articles to get started as a beginner and I managed to fetch XML data from my RESTful API without specifying parameters.In my method that generated the XML resource is below.

@GET @Path("/foods") @Produces(MediaType.APPLICATION_XML) public List<FoodPyramid> getFoodPyramid() {     Session session = HibernateUtil.getSessionFactory().openSession();     trans = session.beginTransaction();     List<FoodPyramid> foodList = session.createQuery("from FoodPyramid").list();     try {         trans.commit();         session.close();     } catch (Exception e) {         session.close();         System.err.println("Food Pyramid fetch " + e);     }     System.err.println("Am in the food modal. . . . . . . .");     return foodList; } 

Now when I tried to pass parameter in the interface

@GET("user/{username}/{password}") Call<List<UserCredentail>> getUserOuth(@Query("username") String username, @Query("password") String password);   

It failed to run,no data was receive by a client . It took me a week trying to fix it though by using a non parameter call fetched the resources; So tried to change it to:

@GET("user/{username}/{password}") Call<List<UserCredentail>> getUserOuth(@Path("username") String username, @Path("password") String password);   

and it worked fine. So My question is: When do I need to use @Query and @Path Annotation in retrofit 2?

like image 618
Mwesigye John Bosco Avatar asked Jun 08 '16 09:06

Mwesigye John Bosco


People also ask

What is @query in retrofit?

Retrofit uses @Query annotation to define query parameters for requests. Query parameters are defined before method parameters. In annotation, we pass the query parameter name which will be appended in the URL.

How do you pass body in GET request retrofit on Android?

This means your @GET or @DELETE should not have @Body parameter. You can use query type url or path type url or Query Map to fulfill your need. Else you can use other method annotation.


2 Answers

Consider this is the url:

www.app.net/api/searchtypes/862189/filters?Type=6&SearchText=School

Now this is the call:

@GET("/api/searchtypes/{Id}/filters") Call<FilterResponse> getFilterList(           @Path("Id") long customerId,           @Query("Type") String responseType,           @Query("SearchText") String searchText ); 

So we have:

www.app.net/api/searchtypes/{Path}/filters?Type={Query}&SearchText={Query} 

Things that come after the ? are usually queries.

like image 55
Nongthonbam Tonthoi Avatar answered Oct 22 '22 01:10

Nongthonbam Tonthoi


For example:

@GET("/user/{username}?type={admin}") 

Here username is the path variable, and type is the query variable

@GET("/user/{username}?type={admin}") void getUserOuth(@Path("username") String username, @Query("type") String type) 
like image 28
Nikson Kanti Paul Avatar answered Oct 22 '22 00:10

Nikson Kanti Paul