I am trying to send a request to the Google GeoCode API using Retrofit. The service interface looks like this:
public interface FooService {
@GET(\"
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:
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:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
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);
}
@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.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
Complete working example in Kotlin, I have replaced my API keys with 1111...
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)
}
}
})