Retrofit的GET请求:
情景:在新闻app中要获取某个用户收藏的文章信息。
这个请求我们使用的是get请求,用户的授权信息放到请求的Headers中;其他参数比如offset-偏移起始位置,limit - 返回最多结果数等参数都放在 LinkedHashMap集合中。
第一步:初始化retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)// http://dev1.baidu.com:4000
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
第二步:携带参数赋值
DataBean dataBean = AppUtils.getClassFromJson(...)
String headStr = dataBean.getToken_type() + " " + dataBean.getAccess_token();
LinkedHashMap<String, Integer> parms = new LinkedHashMap<>();
parms.put("offset", offset);
parms.put("limit", limit);
parms.put("simplemode", simplemode == true ? 1 : 0);
第三步:创建请求接口RequestCollectList
public interface RequestCollectList {
@GET("/v1.0/user/favorite/list")
Call<RspCollectList> contributors(@Header("Authorization") String authorization, @QueryMap Map<String, Integer> parms);
}
第四步:创建返回json数据的Bean类RspCollectList
1、利用Postman发送请求拿到返回json数据;
2、复制json数据,通过GsonFormat插件自动生成Bean类;
这样就轻松生成了返回的JavaBean类。
第五步:发送请求
Call<RspCollectList> call = request.contributors(headStr, parms);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
} else {
response.body();// body节点中是返回的数据
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
到此一个GET请求大致完毕了。
Retrofit的POST请求:
情景:在新闻app某个页面中要点击收藏按钮跟服务器交互实现收藏功能。
该请求事件我们使用POST请求,这个请求中要携带用户的授权信息放到请求的Headers中,通过post携带一个json字符串(字段1:content_type;字段2:content_id)到服务器。
第一步:retrofit对象生成与上面get请求获取方式一样;
第二步:通过postman获取返回数据并用GsonFormat生成JavaBean类RspSaveCollectArticle;
其中post请求携带字符串如下:
[{"content_type":0, "content_id":32889}]
第三步:创建请求接口RequestSaveCollectArticle
public interface RequestSaveCollectArticle {
@Headers("content-type:application/json")
@POST("/v1.0/user/favorite/save")
Call<RspSaveCollectArticle> contributors(@Header("Authorization") String authorization, @Body RequestBody jsonBody);
}
第四步:参数生成
用户授权信息同上;
被携带json数据创建如下
RspSaveCollectArticle.DataBean favorite = new RspSaveCollectArticle.DataBean();
favorite.setContent_type(content_type);
favorite.setContent_id(content_id);
RequestBody jsonRequestBody = RequestBody.create(MediaType.parse("application/json"), "[" + AppUtils.getJsonFromClass(favorite) + "]");
第五步:请求
Call<RspSaveCollectArticle> call = request.contributors(headStr, jsonRequestBody);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
} else {
response.body();// body节点中是返回的数据
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
关于postman和GsonFormatter如何使用可以先查询网站,后续可能会写相关文章介绍。
本文详细介绍了如何使用Retrofit发起GET与POST请求,并通过具体案例展示了新闻应用中收藏功能的具体实现步骤。
334

被折叠的 条评论
为什么被折叠?



