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

时间:2016-12-14 14:13:11

标签: 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.

我的网址: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);

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

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

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

3 个答案:

答案 0 :(得分:5)

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

  

URL查询字符串不得包含替换块。用于动态查询   参数使用@Query

因此,在这种情况下使用@Path注释也无法工作。您可以像第一种方法一样使用@Query注释动态分配查询参数。您可以使用@Path注释(如

)仅动态应用Path参数
@GET("data/{version}/")
Call<Weather> getWeatherReport1(@Path("version") String version);

答案 1 :(得分:0)

您在查询字符串(HTTP url params)中发送params的第一种方法,第二种方法是作为路径参数(REST)发送。

有关详细信息,请查看此处:https://en.wikipedia.org/wiki/Query_string

Rest Standard: Path parameters or Request parameters

因此,如果端点支持路径参数,则第二种方法应为:

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

答案 2 :(得分:0)

如错误所示,您不得在动态查询字符串中放置动态查询参数。

替换块,即{}必须与路径参数一起使用。 你混淆了查询和路径参数,这是无效的,因此也就是错误。

AS Agustin建议,如果您的终端支持路径参数,请使用他提供的方法