Android 使用参数进行改造和 GET
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24100372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrofit and GET using parameters
提问by Perry Hoekstra
I am trying to send a request to the Google GeoCode API using Retrofit. The service interface looks like this:
我正在尝试使用 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);
}
When I call the service:
当我打电话给服务时:
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) {
}
});
I receive the following stacktrace:
我收到以下堆栈跟踪:
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: Retrofit: multiple query parameters in @GET command?but it did not seem applicable.
我看了一下 StackOverflow 的问题:Retrofit: multiple query parameters in @GET command? 但它似乎并不适用。
I took the code pretty much verbatim from here: http://square.github.io/retrofit/so I am a bit of a loss to understand the issue.
我从这里逐字地获取了代码:http: //square.github.io/retrofit/,所以我对理解这个问题有点茫然。
Thoughts?
想法?
回答by Bart Kiers
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
AFAIK,{...}
只能用作路径,不能用作查询参数。试试这个:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
If you have an unknown amount of parameters to pass, you can use do something like this:
如果您有未知数量的参数要传递,您可以使用以下方法:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
回答by madhu527
@QueryMap
worked for me instead of FieldMap
@QueryMap
为我工作而不是 FieldMap
If you have a bunch of GET params, another way to pass them into your url is a HashMap
.
如果您有一堆 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.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
回答by TheIT
I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147
, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:
我还想澄清一下,如果您要构建复杂的 url 参数,则需要手动构建它们。即,如果您的查询是example.com/?latlng=-37,147
,而不是单独提供 lat 和 lng 值,您将需要在外部构建 latlng 字符串,然后将其作为参数提供,即:
public interface LocationService {
@GET("/example/")
void getLocation(@Query(value="latlng", encoded=true) String latlng);
}
Note the encoded=true
is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:
注意encoded=true
是必要的,否则改造将在字符串参数中编码逗号。用法:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
回答by Hitesh Sahu
Complete working example in Kotlin, I have replaced my API keys with 1111...
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)
}
}
})