Retrofit y OBTENER el uso de parámetros
Estoy tratando de enviar una solicitud a la API de GeoCode de Google usando Retrofit. La interfaz de servicio se ve así:
public interface FooService {
@GET("/maps/api/geocode/json?address={zipcode}&sensor=false")
void getPositionByZip(@Path("zipcode") int zipcode, Callback<String> cb);
}
Cuando llamo al servicio:
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) {
}
});
Recibo el siguiente 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
Eché un vistazo a la pregunta de StackOverflow: Retrofit: ¿múltiples parámetros de consulta en el comando @GET? pero no parecía aplicable.
Tomé el código literalmente de aquí: http://square.github.io/retrofit / así que estoy un poco de una pérdida para entender el problema.
Pensamientos?
3 answers
AFAIK, {...}
solo se puede usar como una ruta, no dentro de un query-param. Prueba esto en su lugar:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
Si tiene una cantidad desconocida de parámetros para pasar, puede usar hacer algo como esto:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 13:02:29
@QueryMap
funcionó para mí en lugar de FieldMap
Si tienes un montón de GET params, otra forma de pasarlos a tu url es un 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.
});
}
}
La URL llamada será http://www.example.com/thing/?key1=val1&key2=val2
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-23 03:56:20
También quería aclarar que si tiene parámetros de url complejos para construir, tendrá que construirlos manualmente. ie si su consulta es example.com/?latlng=-37,147
, en lugar de proporcionar los valores lat y lng individualmente, deberá construir la cadena latlng externamente, luego proporcionarla como un parámetro, ie:
public interface LocationService {
@GET("/example/")
void getLocation(@Query(value="latlng", encoded=true) String latlng);
}
Tenga en cuenta que es necesario encoded=true
, de lo contrario retrofit codificará la coma en el parámetro string. Uso:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 20:48:41