2013-11-14 76 views
40

我正在使用Retrofit和Robospice在我的android應用程序中進行API調用。所有@POST方法效果很好,在URL中沒有任何參數的@GET命令也是如此,但我無法獲得任何@GET調用來處理末尾的參數!改進:@GET命令中的多個查詢參數?

例如,如果我的API路徑是「我/ API /呼叫/」,我想2個參數「參數1」,並在URL「參數2」,get調用會是什麼樣子:

http://www.example.com/my/api/call?param1=value1&param2=value2

所以我有我的設置界面@ GET像這樣:

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

,但我得到一個錯誤說
「要求網絡執行過程中出現的異常:URL查詢字符串」 /my/api/call?param1={p1}&param2={p2}「的方法getMyThing可能沒有repla ced塊「。

我在做什麼錯?

回答

98

您應該使用這樣的語法:

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

指定的查詢參數中的URL僅當你知道這兩個關鍵和價值,他們是固定的。

+2

我得到現在以下錯誤:11-14 10:29:48.626:電子// RequestRunner.java:134(31776):10:29: 48.630線程-11782請求網絡執行期間發生異常:null 我絕對在我的spicemanager中設置界面,不知道什麼可能是空的...... – AndroidNoob

+2

我不確定,對不起。我從未使用過RoboSpice。我只是在這裏爲了翻新:) –

+0

嗨傑克,那我們完美的情況下,你必須自己構造查詢參數,但是如果它們是在previosly給你的呢?想象一下模板響應,它告訴你從哪裏獲取信息,併爲你設置這些參數。所以/ my/api/call?param1 = {p1}&param2 = {p2}實際上不是由您手動創建的,而是在另一個調用的響應中提供給您的。 –

5

不要在GET-URL中編寫查詢參數。像這樣做:

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

如果你有一堆GET則params的,另一種方式將它們傳遞到您的網址是一個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. 
     }); 
    } 
} 

所謂的URL將http://www.example.com/thing/?foo=bar&baz=qux