@Query
和@Path注解来处理
单个,多个甚至可选的查询参数和路径参数请求@Query
注释来定义请求的查询参数。查询参数在方法参数之前定义。在注释中,我们传递将附加在URL中的查询参数名称。
@Query
我们要发送的参数一样多的注释
https://<DOMAIN>/api/users?page=2&per_page=10
@GET("/api/users")
public Call<UsersApiResponse> getUsers(@Query("per_page") int pageSize,
@Query("page") int currentPage);
实际API调用时传递参数值。假设我们想要发送多个具有相同名称的参数,例如userId
。这是非常罕见的情况 - 这仍然可以帮助我们遇到这个要求。
https://<DOMAIN>/api/users?userId=1&userId=2&userId=3
在服务器上,它将被收到userId = [1,2,3]
。
@GET("/api/users")
public Call<UsersApiResponse> getUsers(@Query("userId") List<Integer> ids);
@Query
注释采用属性即encoded
。它属于boolean
类型,无论是真还是假。null
值。null
在创建请求时,Retrofit会跳过参数并忽略它们。
例如,调用我们不能传递
'null'
给原始类型。因此,始终建议使用包装类作为参数类型。
service.getUsers(null, null)
将导致'https://DOMAIN/api/users'
。
@Path
注释表示。它们也来自方法参数。它们在URL路径段中被命名为替换。null
。@Path
在完整API路径解析之前修改注释中传递的值并对其进行URL编码。
@GET("/api/users/{id}")
public Call<UserApiResponse> getUser(@Path("id") Long id);
使用service.getUser(1)调用上面的API会产生'/ api / users / 1'。
@Path
注释采用属性即encoded
。它属于boolean
类型,无论是真还是假。@GET("/user/{name}")
Call<ResponseBody> getUserByName(@Path(value="name") String name);
//OR - encoded is default 'true'
@GET("/user/{name}")
Call<ResponseBody> getUserByName(@Path(value="name", encoded=true) String name);
service.getUserByName("John+Doe")
将被解析'/user/John%2BDoe'
。@GET("/user/{name}")
Call<ResponseBody> getUserByName(@Path(value="name", encoded=false) String name);
service.getUserByName("John+Doe")
将被解决'/user/John+Doe'
。https://www.leftso.com/article/666.html