neo
neo

Reputation: 1404

How to create request URL using Retrofit?

I want to create GET request to this API: http://maps.googleapis.com/maps/api/geocode/json?latlng=myLatitude,myLongitude&sensor=true

Instead of myLatitude and myLongitude, I need to put my own values. Below you can see how I tried to do request using Retrofit:

ApiInterface:

@GET("json?latlng={lat},{long}&sensor=true")
Call<JsonArray> getApproximateLocations(@Query(value = "lat" , encoded = true) String lat, @Query(value = "long" , encoded = true) String lon);

My request:

Retrofit retrofit = new Retrofit.Builder().baseUrl(getString(R.string.location_base_api)).addConverterFactory(GsonConverterFactory.create())
            .build();


    ApiInterface apiInterface = retrofit.create(ApiInterface.class) ;

    mapsApiInterface.getApproximateLocations(String.valueOf(lat),String.valueOf(lon)).enqueue(new Callback<JsonArray>() {
        @Override
        public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {

        }

        @Override
        public void onFailure(Call<JsonArray> call, Throwable throwable) {

        }
    });

My base URL is: http://maps.googleapis.com/maps/api/geocode/.

The result of this code is following error: java.lang.IllegalArgumentException: URL query string "latlng={lat},{long}&sensor=true" must not have replace block. For dynamic query parameters use @Query.

So, why I get this error and how to solve the problem?

Upvotes: 0

Views: 381

Answers (2)

Viktor Yakunin
Viktor Yakunin

Reputation: 3266

@GET("json?latlng={lat},{long}&sensor=true")
Call<JsonArray> getApproximateLocations(@Query(value = "lat" , encoded = true) String lat, @Query(value = "long" , encoded = true) String lon);

should be like:

@GET("json")
Call<JsonArray> getApproximateLocations(
    @Query(value = "latlng" , encoded = true) String latLng/* pass formatted string here (e.g. 2.1367,2.3199 */, 
    @Query(value = "sensor") boolean isSensor);

Upvotes: 1

Sara Tirmizi
Sara Tirmizi

Reputation: 427

Do like this:

@GET( Constants.GET_ADDRESS_BY_LOCATION )
    ServiceCall<Response> getAddress(@Query(Constants.PATH_LATLNG) String latlng, @Query(Constants.PATH_LANGUAGE) String language , @Query(Constants.KEY_GOOGLE_MAP_API) String key);

GET_ADDRESS_BY_LOCATION is API while other constants are parameters required

Upvotes: 1

Related Questions