我尝试了两种类型的值传递给一个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.为什么第二种方法不起作用?
发布于 2016-12-14 14:35:40
第二种方法不起作用,因为
URL查询字符串不能有替换块。对于动态查询参数,请使用@Query
因此,在这种情况下也使用@Path注释是行不通的。您可以使用@Query注释(如第一个方法)动态地分配查询参数。您可以使用@Path注释动态地应用路径参数,如
@GET("data/{version}/")
Call<Weather> getWeatherReport1(@Path("version") String version);
发布于 2016-12-14 14:21:33
第一个方法是在查询字符串中发送params (HTTP url params),第二个方法是发送路径params (REST)。
有关更多信息,请在此处查看: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);
发布于 2016-12-14 16:34:08
正如错误提示的那样,您不能在url查询字符串中放置动态查询参数。
必须用路径旁线替换块i.e {}。您正在混合查询和路径参数,这是无效的,因此出现了错误。
正如奥古斯丁所建议的,如果您的端点支持路径参数,请使用他提供的方法。
https://stackoverflow.com/questions/41144738
复制相似问题