文章出處

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'
  2. 添加權限

    <uses-permission android:name="android.permission.INTERNET"/>
  3. 創建實體類
    • 使用GsonFormat創建實體類,這里就不詳細說了。
  4. 創建Retrofit對象

    //1.創建一個Retrofit對象
    Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())//解析方法
        .baseUrl("http://api.m.mtime.cn/PageSubArea/TrailerList.api/")
        .build();
  5. 聲明接口

    //2.聲明一個接口
    public  interface IItemService{
        /**
         * 根據movieId獲取對應的信息數據
         * @param movieId
         * @return
         */
        @GET("Item/{movieId}")
        Call<Item> getItem(@Path("movieId") String movieId);
    }
  6. 創建訪問API請求

    IItemService service = retrofit.create(IItemService.class);
    Call<Item> call = service.getItem("65094");
  7. 調用
    • 同步調用

      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());
      }
      });
  8. 取消請求

    call.cancel();

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()