改造:@GET命令中的多个查询参数?

时间:2013-11-14 10:19:15

标签: android api get retrofit robospice

我正在使用Retrofit和Robospice在我的Android应用程序中进行API调用。所有的@POST方法都很有用,所以@GET命令在URL中没有任何参数也是如此,但是我无法获得任何@GET调用来使用参数!

例如,如果我的API路径是“my / api / call /”并且我想在URL中使用2个参数“param1”和“param2”,那么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);

但是我收到错误说“请求网络执行期间发生异常:方法getMyThing上的URL查询字符串”/my/api/call?param1={p1}&param2={p2}“可能没有替换阻止。”

我做错了什么?

5 个答案:

答案 0 :(得分:113)

您应该使用以下语法:

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

在URL中指定查询参数仅适用于您知道密钥和值并且它们已修复的情况。

答案 1 :(得分:14)

如果您有一堆GET参数,另一种将它们传递到您的网址的方法是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.
       });
    }
}

调用的网址为http://www.example.com/thing/?foo=bar&baz=qux

答案 2 :(得分:6)

不要在GET-URL中编写查询参数。这样做:

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

答案 3 :(得分:0)

您可以创建一个参数图,并按以下方式发送:

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);

答案 4 :(得分:0)

使用 Java

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

使用 Kotlin 协程

 @GET("/my/api/call")
 suspend fun getSearchProduct(@Query("p1") p1: String , @Query("p2") p2: String )
相关问题