JSON的字符串如果有这么长:
http://baobab.kaiyanapp.com/api/v4/tabs/selected?udid=11111&vc=168&vn=3.3.1&deviceModel=Huawei6&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market&system_version_code=20
那么使用Retrofit的时候,会感到拼接字符串非常麻烦。而拆分的规律如下:
1.基本的URL地址的一部分:
http://baobab.kaiyanapp.com/
需要注意的是后面一定要跟/ 而可变的不需要加。具体可参见这张图示:
Retrofit接口中URL的定义方式:
2.网络请求的URL地址一部分:
api/v4/tabs/selected?
3.?(问号) 后面拼接字符串的URL地址:
udid=11111&vc=168&vn=3.3.1&deviceModel=Huawei6&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market&system_version_code=20
同样需要注意的是如果你是直接使用的话,可以不拼接字符串,直接在接口HttpbinService的@GET()里面填写就可以的,具体的可以参考我下面的写的代码。
如果只需要json字符串直接的显示,不需要动态的改变后面拼接参数的值得大小的话。(可以适配各种json的我不会...)
可以有以下代码:在接口HttpbinService:
public interface HttpbinService {
@GET("api/v4/tabs/selected?udid=11111&vc=168&vn=3.3.1&deviceModel=Huawei6&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market&system_version_code=20")
Call<ResponseBody> getData();
}
而在网络请求端,也是activity/fragment类中,有方法如下:
标准的按照如下5步来:
1.定义一个接口(封装URL地址和数据请求)
2.实例化Retrofit
3.通过retrofit实例创建接口服务对象
4.接口服务对象调用接口中方法,获得Call对象
5.Call对象执行请求(异步、同步)
fragment/activity类中:
private void loadData() {
//实例化retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://baobab.kaiyanapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
//通过retrofit实例创建接口服务对象
HttpbinService httpbinService = retrofit.create(HttpbinService.class);
//接口服务对象调用接口中方法,获得Call对象
Call<ResponseBody> call = httpbinService.getData();
//Call对象执行请求(异步、同步)
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = new String(response.body().bytes());
VideoBean videoBean = new Gson().fromJson(json, VideoBean.class);
//此处是解析json获取网络视频
List<VideoBean.ItemListDTO> itemListDTOList = videoBean.getItemList();
Log.e("retrofit获取到的数据", json);
for (int i = 0; i < itemListDTOList.size(); i++) {
VideoBean.ItemListDTO listBean = itemListDTOList.get(i);
if (listBean.getType().equals("video")) {
mDatas.add(listBean);
}
}
adapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
}
}
}
相对okhttp,retrofit会对responseBody进行自动的Gson解析,自动的完成线程的切换。