使用参数进行改造和GET


92

我正在尝试使用Retrofit向Google GeoCode API发送请求。服务界面如下所示:

public interface FooService {    
    @GET("/maps/api/geocode/json?address={zipcode}&sensor=false")
    void getPositionByZip(@Path("zipcode") int zipcode, Callback<String> cb);
}

当我致电服务时:

OkHttpClient okHttpClient = new OkHttpClient();

RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constants.GOOGLE_GEOCODE_URL).setClient(new OkClient(okHttpClient)).build();

FooService service = restAdapter.create(FooService.class);

service.getPositionByZip(zipCode, new Callback<String>() {
    @Override public void success(String jsonResponse, Response response) {
       ...
    }
@Override public void failure(RetrofitError retrofitError) {
    }
});

我收到以下堆栈跟踪:

06-07 13:18:55.337: E/AndroidRuntime(3756): FATAL EXCEPTION: Retrofit-Idle
06-07 13:18:55.337: E/AndroidRuntime(3756): Process: com.marketplacehomes, PID: 3756
06-07 13:18:55.337: E/AndroidRuntime(3756): java.lang.IllegalArgumentException: FooService.getPositionByZip: URL query string "address={zipcode}&sensor=false" must not have replace block.
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:120)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.parsePath(RestMethodInfo.java:216)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.parseMethodAnnotations(RestMethodInfo.java:162)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at 

我看了一下StackOverflow问题:改进:@GET命令中有多个查询参数?但它似乎不适用。

我从这里逐字逐句地获取了代码:http : //square.github.io/retrofit/,所以对于理解这个问题我有些茫然。

有什么想法吗?

Answers:


154

AFAIK,{...}只能用作路径,不能在查询参数内使用。尝试以下方法:

public interface FooService {    

    @GET("/maps/api/geocode/json?sensor=false")
    void getPositionByZip(@Query("address") String address, Callback<String> cb);
}

如果您要传递的参数数量未知,则可以执行以下操作:

public interface FooService {    

    @GET("/maps/api/geocode/json")
    @FormUrlEncoded
    void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}

如何添加多个查询参数
Gilberto Ibarra 2015年

2
@GilbertoIbarra错误,通过添加更多内容:void getPositionByZip(@Query("address") String address, @Query("number") String number, Callback<String> cb);
Bart

9
FormUrlEncoded只能在带有请求正文(例如@POST)的HTTP方法上指定
jiashie '17

8
错误的答案,@ FormUrlEncoded不能与GET
一起

1
@FormUrlEncoded不适用于@GET注释
Black_Zerg '18

40

@QueryMap 为我工作,而不是 FieldMap

如果您有一堆GET参数,则将它们传递到url中的另一种方法是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> params, 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("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

调用的URL将为http://www.example.com/thing/?key1=val1&key2=val2


4

我还想澄清一下,如果要构建复杂的url参数,则需要手动构建它们。也就是说,如果您的查询是example.com/?latlng=-37,147,而不是分别提供lat和lng值,则需要在外部构建latlng字符串,然后将其作为参数提供,即:

public interface LocationService {    
    @GET("/example/")
    void getLocation(@Query(value="latlng", encoded=true) String latlng);
}

请注意,这encoded=true是必需的,否则改造将在字符串参数中对逗号进行编码。用法:

String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);

1

Kotlin中完整的工作示例,我用1111替换了API密钥...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

1
可以将getWeather(params)方法定义放得更清楚吗?
supro_96年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.