Retrofit and GET using parameters

AndroidGetRetrofit

Android Problem Overview


I am trying to send a request to the Google GeoCode API using Retrofit. The service interface looks like this:

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: https://stackoverflow.com/questions/19975046/java-retrofit-robospice-multiple-parameters-in-get-command but it did not seem applicable.

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.

Thoughts?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

@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

Solution 3 - Android

@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>

Retrofit + Kotlin + RestAPI example that works for me.

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

Solution 4 - Android

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

Solution 5 - Android

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)

                }
            }

        })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPerry HoekstraView Question on Stackoverflow
Solution 1 - AndroidBart KiersView Answer on Stackoverflow
Solution 2 - Androidmadhu527View Answer on Stackoverflow
Solution 3 - AndroidJ A S K I E RView Answer on Stackoverflow
Solution 4 - AndroidTheITView Answer on Stackoverflow
Solution 5 - AndroidHitesh SahuView Answer on Stackoverflow