在Android Retrofit库中将值传递给URL之间的差异

M.A*_*ali 3 android retrofit retrofit2

我已尝试将两种类型的值传递给Android Retrofit库中的URL,方法1执行时没有任何错误但方法2抛出错误.

我通过查询键名称发送参数值,方法1中带注释参数的值,方法2中API端点的变量替换

方法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.
Run Code Online (Sandbox Code Playgroud)

我的网址:data/2.5/weather?lat = 77.603287&lon = 12.97623&appid = f5138&units = metric

方法1 :(执行良好)

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

方法2 :(错误)

@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);
Run Code Online (Sandbox Code Playgroud)

我尝试过@Path以及第二种方法.

我的问题是1.这两种方法有什么区别?2.为什么第二种方法不起作用?

小智 7

第二种方法不起作用,因为

URL查询字符串不能具有替换块.对于动态查询参数,请使用@Query

因此在这种情况下使用@Path注释也行不通.您可以像第一种方法一样使用@Query注释动态分配查询参数.您可以使用@Path注释来动态应用Path参数

@GET("data/{version}/")
Call<Weather> getWeatherReport1(@Path("version") String version);
Run Code Online (Sandbox Code Playgroud)