2016-12-14 60 views
1

我已经尝试了两种类型的值传递给Android Retrofit库中的URL,方法1执行时没有任何错误,但方法2抛出错误。在Android Retrofit库中传递值到URL的差异

我发送参数值通过查询键名与注释参数的值在方法1和可变取代的API端点在方法2

错误由方法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. 

我网址:数据/ 2.5 /天气LAT = 77.603287 & LON = 12.97623 &的appid = f5138 &单位=度量

方法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.为什么第二种方法不起作用?

+0

理论上路径替换查询应该这样做。第一个为你构造一个查询字符串,第二个是你手动创建的。 –

回答

4

第二种方法是行不通的因为

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

所以在这种情况下也使用@Path注释将不起作用。您可以像使用第一种方法一样使用@Query注释来动态分配查询参数。您可以使用@Path注释动态应用路径参数,如

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

正确,正确的答案,我正在寻找 – Suman

0

您在查询字符串(HTTP url 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); 
0

由于错误提示,您不能在URL查询字符串中放置动态查询参数。

替换块即{}必须与路径参数一起使用。 您正在混合查询和路径参数,这是无效的,因此错误。

AS奥古斯丁建议,如果你的终端支持路径参数,使用由他提供的方法