使用参数进行改进和 GET

我试图发送一个请求到 GoogleGeoCodeAPI 使用龟裂。服务接口如下:

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

I took a look at the StackOverflow question: 修改:@GET 命令中的多个查询参数? but it did not seem applicable.

我几乎是一字不差地从这里的代码: http://square.github.io/retrofit/,所以我有点不明白这个问题。

有什么想法吗?

184828 次浏览

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

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a 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 将被称为 like-http://www.example.com/thing/?key1=val1&key2=val2

我还想说明的是,如果要构建复杂的 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);

科特林中的完整工作示例,我已经用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)


}
}


})
@Headers(
"Accept: application/json",
"Content-Type: application/json",
"Platform: android")
@GET("api/post/post/{id}")
fun showSelectedPost(
@Path("id") id: String,
@Header("Version") apiVersion: Int
): Call<Post>

对我来说有效的翻新 + Kotlin + RestAPI示例。

I hope this @Header, @GET, @Path with parameters will help someone also)