Difference between passing values to URL in Android Retrofit library

10.6k Views Asked by At

I have tried two type of value passing to an URL in Android Retrofit library, method 1 is executed without any error but method 2 throw error.

I sent parameter values by query key name with the value of the annotated parameter in Method 1 and variable substitution for the API endpoint in Method 2

Error thrown by method 2:

java.lang.IllegalArgumentException: URL query string "appid={apikey}&lat={lat}&lon={lon}&units={units}" must not have replace block. For dynamic query parameters use @Query.

My URL : data/2.5/weather?lat=77.603287&lon=12.97623&appid=f5138&units=metric

Method 1: (Executed well)

@GET("data/2.5/weather")
Call<Weather> getWeatherReport(@Query("lat") String lat,
                               @Query("lon") String lng,
                               @Query("appid") String appid,
                               @Query("units") String units);

Method 2: (Error)

@GET("data/2.5/weather?appid={apikey}&lat={lat}&lon={lon}&units={units}")
Call<Weather> getWeatherReport1(@Query("apikey") String apikey,
                               @Query("lat") String lat,
                               @Query("lon") String lng,
                               @Query("units") String units);

I have tried @Path as well as in the second method.

My Questions are 1.What is the difference between both the methods? 2.Why does the second method did not worked?

3

There are 3 best solutions below

0
On BEST ANSWER

Second method won't work because

URL query string must not have replace block. For dynamic query parameters use @Query

So also using @Path annotation in that case won't work. You can dynamically assign query parameters by using @Query annotation like in first method. You can dynamically apply only Path parameters with use of @Path annotation like

@GET("data/{version}/")
Call<Weather> getWeatherReport1(@Path("version") String version);
0
On

As the error suggests, you must not place dynamic query parameters in the url query string.

Replace blocks i.e {} must be used with path params. You are mixing up query and path params which is invalid and hence the error.

AS Agustin suggested, if your endpoint supports path params, use the method provided by him

0
On

The first method you send the params in Query strings (HTTP url params), the second you send as path params (REST).

For more information take look here: https://en.wikipedia.org/wiki/Query_string

Rest Standard: Path parameters or Request parameters

So, if the endpoint supports the path params, the second method should be:

@GET("data/2.5/weather?appid={apikey}&lat={lat}&lon={lon}&units={units}")
Call<Weather> getWeatherReport1(@Path("apikey") String apikey,
                               @Path("lat") String lat,
                               @Path("lon") String lng,
                               @Path("units") String units);