android query方法参数,Android】Retrofit网络请求参数注解,@Path、@Query、@QueryMap...(转)...

对Retrofit已经使用了一点时间了,是时候归纳一下各种网络请求的service了。

下面分为GET、POST、DELETE还有PUT的请求,说明@Path、@Query、@QueryMap、@Body、@Field的用法。

初始化Retrofit

String BASE_URL = "http://102.10.10.132/api/";

Retrofit retrofit = new Retrofit.Builder()

.baseUrl(BASE_URL)

.build();

GET

样式1(一个简单的get请求)

@GET("News")

Call getItem();

样式2(URL中有参数)

@GET("News/{newsId}")

Call getItem(@Path("newsId") String newsId);

@GET("News/{newsId}/{type}")

Call getItem(@Path("newsId") String newsId, @Path("type") String type);

样式3(参数在URL问号之后)

@GET("News")

Call getItem(@Query("newsId") String newsId);

@GET("News")

Call getItem(@Query("newsId") String newsId, @Query("type") String type);

样式4(多个参数在URL问号之后,且个数不确定)

@GET("News")

Call getItem(@QueryMap Map map);

也可以

@GET("News")

Call getItem(

@Query("newsId") String newsId,

@QueryMap Map map);

POST

样式1(需要补全URL,post的数据只有一条reason)

@FormUrlEncoded

@POST("Comments/{newsId}")

Call reportComment(

@Path("newsId") String commentId,

@Field("reason") String reason);

样式2(需要补全URL,问号后加入access_token,post的数据只有一条reason)

@FormUrlEncoded

@POST("Comments/{newsId}")

Call reportComment(

@Path("newsId") String commentId,

@Query("access_token") String access_token,

@Field("reason") String reason);

样式3(需要补全URL,问号后加入access_token,post一个body(对象))

@POST("Comments/{newsId}")

Call reportComment(

@Path("newsId") String commentId,

@Query("access_token") String access_token,

@Body CommentBean bean);

DELETE

样式1(需要补全URL)

@DELETE("Comments/{commentId}")

Call deleteNewsCommentFromAccount(

@Path("commentId") String commentId);

样式2(需要补全URL,问号后加入access_token)

@DELETE("Comments/{commentId}")

Call deleteNewsCommentFromAccount(

@Path("commentId") String commentId,

@Query("access_token") String access_token);

样式3(带有body)

@HTTP(method = "DELETE",path = "Comments",hasBody = true)

Call deleteCommont(

@Body CommentBody body

);

CommentBody:需要提交的内容,与Post中的Body相同

PUT(这个请求很少用到,例子就写一个)

@PUT("Accounts/{accountId}")

Call updateExtras(

@Path("accountId") String accountId,

@Query("access_token") String access_token,

@Body ExtrasBean bean);

总结

@Path:所有在网址中的参数(URL的问号前面),如:

http://102.10.10.132/api/Accounts/{accountId}

@Query:URL问号后面的参数,如:

http://102.10.10.132/api/Comments?access_token={access_token}

@QueryMap:相当于多个@Query

@Field:用于POST请求,提交单个数据

@Body:相当于多个@Field,以对象的形式提交

Tips

Tips1

使用@Field时记得添加@FormUrlEncoded

Tips2

若需要重新定义接口地址,可以使用@Url,将地址以参数的形式传入即可。如

@GET

Call> getActivityList(

@Url String url,

@QueryMap Map map);

Call> call = service.getActivityList(

"http://115.159.198.162:3001/api/ActivitySubjects", map);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值