Retrofit2的基本使用

Retrofit模型简介

  1. POJO或模型实体类 : 从服务器获取的JSON数据将被填充到这种类的实例中。
  2. 接口 : 我们需要创建一个接口来管理像GET,POST...等请求的URL,这是一个服务类。
  3. RestAdapter类 : 这是一个REST客户端(RestClient)类,retrofit中默认用的是Gson来解析JSON数据,你也可以设置自己的JSON解析器。

使用

  1. 添加依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
  1. 添加权限
<uses-permission android:name="android.permission.INTERNET"/>
  1. 创建实体类
    - 使用GsonFormat创建实体类,这里就不详细说了。

  2. 创建Retrofit对象

//1.创建一个Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())//解析方法
        .baseUrl("http://api.m.mtime.cn/PageSubArea/TrailerList.api/")
        .build();
  1. 声明接口
//2.声明一个接口
    public  interface IItemService{
        /**
         * 根据movieId获取对应的信息数据
         * @param movieId
         * @return
         */
        @GET("Item/{movieId}")
        Call<Item> getItem(@Path("movieId") String movieId);
    }
  1. 创建访问API请求
IItemService service = retrofit.create(IItemService.class);
Call<Item> call = service.getItem("65094");
  1. 调用
    - 同步调用
Item bean = call.execute();
-    异步调用
call.enqueue(new Callback<Item>() {
    @Override
    public void onResponse(Call<Item> call, Response<Item> response) {
        Item bean = response.body();
        Log.i("输出", bean.toString());
    }
    @Override
    public void onFailure(Call<Item> call, Throwable t) {
        Log.i("输出",t.toString());
    }
});
  1. 取消请求
call.cancel();
posted @ 2017-04-17 13:09  Godfunc  阅读(730)  评论(0编辑  收藏  举报