2016-06-08 33 views
10

我是翻新2庫的新手。我讀了幾篇文章,作爲初學者入門,我設法從我的RESTful API獲取XML數據,而無需指定參數。在我的生成XML的方法資源在下面。翻新2 @path Vs @query

@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; 
    } 

現在,當我試圖通過參數在接口

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

它運行失敗,沒有數據是由客戶端接收。我花了一個星期的時間試圖解決它,但通過使用非參數調用獲取資源; 所以試圖將其更改爲

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

它工作得很好。所以我的問題是:何時需要使用@Query@Path翻新2中的註釋?

回答

36

考慮這是網址:

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

現在,這是呼叫:

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

因此,我們有:

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

事情發生在之後?通常是查詢。

1

查詢是使用了URL參數和@Query( 「密碼」)的URL應該是:

user/john?password=**** 

Path是使用,以取代在你的路徑定義的項目,像

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

這裏usernamepath變量和admin是查詢變量

@GET("/user/{username}?type={admin}") 
void getUserOuth(@Path("username") String username, @Query("admin") String type) 
+0

@Paul讓我試驗一下吧。謝謝 –

0

@Path用於當您在後退斜槓後具有'/'動態值的url。示例「http://google.com/index.html/userid。因此,在這個網址/用戶ID是動態的,所以要訪問此網址,您的請求應該是 @Get(「index.html/{userid}」) Calldata(@Path(「userid」)int id);

@Query被用來當你有一個網址有'?'動態值後問號。例如「http://google.com/index.html?userid.So在這個網址?userid是動態的,所以訪問這個url你的請求應該是 @Get(」index.html「) Calldata(@Query(」userid「)int id);