您的位置:首页 > 移动开发 > Android开发

Retrofit2.0 简单使用总结

2017-04-26 10:40 162 查看
原文出处:https://gold.xitu.io/entry/58aac9710ce463006b13914d

初始化Retrofit
String BASE_URL =
"http://102.10.10.132/api/";Retrofit
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) .build();
===================================get请求====================================================
1.直接拼在后面
@GET("News")
Call<NewsBean> getItem();

效果:http://102.10.10.132/api/News
2.(@Path)替换括号内参数

@GET("News/{newsId}")
Call<NewsBean>
getItem(@Path("newsId")
String newsId);

@GET("News/{newsId}/{type}")
Call<NewsBean>
getItem(@Path("newsId")
String newsId, @Path("type")
String type);

效果:http://102.10.10.132/api/News/{资讯id}/{类型}
3.(@Query)相当于 ?a=1&b=2;
@GET("News")
Call<NewsBean>
getItem(@Query("newsId")
String newsId);

效果:http://102.10.10.132/api/News?newsId={资讯id}&type={类型}
4.(@Querymap)多个参数在URL问号之后,且个数不确定;
@GET("News")
Call<NewsBean>
getItem(@QueryMap Map<String, String> map);
@GET("News")
Call<NewsBean>
getItem( @Query("newsId")
String newsId, @QueryMap Map<String, String> map);

===================================POST请求====================================================
1.(@FormUrlEncoded)这个参数必须存在;(@Field)为一个表单;(@Path)这个参数直接替换
@FormUrlEncoded
@POST("Comments/{newsId}")
Call<Comment>
reportComment( @Path("newsId")
String commentId, @Field("reason")
String reason);
效果:http://102.10.10.132/api/Comments/{newsId}
2.(@FormUrlEncoded)这个参数必须存在;(@Field)为一个表单;(@Query)为拼接Url的?a=1&b=2;
@FormUrlEncoded
@POST("Comments/{newsId}")
Call<Comment>
reportComment( @Path("newsId")
String commentId, @Query("access_to
da96
ken")
String access_token, @Field("reason")
String reason);
效果:http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}
3.(@FormUrlEncoded)这个参数必须存在;(@Field)为一个表单;(@Path)这个参数直接替换;(@Body)为一个Bean对象 不常用;
@POST("Comments/{newsId}")
Call<Comment>
reportComment( @Path("newsId")
String commentId, @Query("access_token")
String access_token, @Body CommentBean bean);
效果:http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}

总结
@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

Tip1
使用@Field时记得添加@FormUrlEncoded

Tip2
若需要重新定义接口地址,可以使用@Url,将地址以参数的形式传入即可。如
@GET
Call<List<Activity>> getActivityList( @Url
String url, @QueryMap
Map<String, String> map);
Call<List<Activity>> call = service.getActivityList(
"http://115.159.198.162:3001/api/ActivitySubjects",
map);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android Retrofit2.0