1. 程式人生 > >Android框架之路——Retrofit2.0的初窺(包含Gson)

Android框架之路——Retrofit2.0的初窺(包含Gson)

參考部落格:

實現效果:

      enter image description here

使用姿勢:

   1. 使用教程

  • 新增依賴
    • compile ‘com.squareup.retrofit2:retrofit:2.2.0’
    • compile ‘com.squareup.retrofit2:converter-gson:2.2.0’
  • AndroidStudio新增Gson外掛——GsonFormat

   2. 使用API

  • 功能:根據高校程式碼進行學科專業類排名
  • 返回json如下:

    {
        "rows": [
            {
                "id": 1893,
                "specCode": "",
                "specName": "冶金工程類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "5",
                "univScore": "78"
            },
            {
                "id": 328,
                "specCode": "0303",
                "specName": "社會學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "8",
                "univScore": "77"
            },
            {
                "id": 828,
                "specCode": "0503",
                "specName": "新聞傳播學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "10",
                "univScore": "77"
            },
            {
                "id": 3959,
                "specCode": "1303",
                "specName": "戲劇與影視學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "4",
                "univScore": "77"
            },
            {
                "id": 396,
                "specCode": "0305",
                "specName": "馬克思主義理論類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "17",
                "univScore": "76"
            }
        ]
    }
    

   3. 入門使用Retrofit

  • 定義介面(封裝URL地址和資料請求) :

    @GET("rank_querySpecRankByUniv")
    Call<ResponseBody> querySpecRankByUniv(
            @Query("university.univCode") String univCode,
            @Query("page") int page);
    
  • 例項化Retrofit:

    Retrofit retrofit = new Retrofit.Builder()
             .baseUrl(Constant.BASE_URL)
             .build();
    
  • 通過Retrofit例項建立介面服務物件

    QueryRankService service = retrofit.create(QueryRankService.class);
    
  • ResponseBody中存放著我們請求的資料,呼叫response.body().string()轉化為字串:

     Call<ResponseBody> call = service.querySpecRankByUniv("10280", 1);
     call.enqueue(new Callback<ResponseBody>() {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
             if(response.isSuccessful()){
                 try {
                     String result = response.body().string();
                     mTextView.setText(result);
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
    
         @Override
         public void onFailure(Call<ResponseBody> call, Throwable t) {
    
         }
     });
    

   4. 使用GsonFormat生成Bean

  • 新建Bean類——SpecRank.java
  • 類中右鍵Generate–》GsonFormat,將json樣例拷貝進AS,點選ok即可
  • 生成如下:

    package com.ping.retrofit2.beans;
    
    import java.util.List;
    
    /**
     * SpecRankBean
     * Created by Mr.sorrow on 2017/4/24.
     */
    
    public class SpecRankBean {
    
        private List<RowsBean> rows;
    
        public List<RowsBean> getRows() {
            return rows;
        }
    
        public void setRows(List<RowsBean> rows) {
            this.rows = rows;
        }
    
        public static class RowsBean {
            /**
             * id : 1893
             * specCode :
             * specName : 冶金工程類
             * univCode : 10280
             * univName : 上海大學
             * univRank : 5
             * univScore : 78
             */
    
            private int id;
            private String specCode;
            private String specName;
            private String univCode;
            private String univName;
            private String univRank;
            private String univScore;
    
            public int getId() {
                return id;
            }
    
            public void setId(int id) {
                this.id = id;
            }
    
            public String getSpecCode() {
                return specCode;
            }
    
            public void setSpecCode(String specCode) {
                this.specCode = specCode;
            }
    
            public String getSpecName() {
                return specName;
            }
    
            public void setSpecName(String specName) {
                this.specName = specName;
            }
    
            public String getUnivCode() {
                return univCode;
            }
    
            public void setUnivCode(String univCode) {
                this.univCode = univCode;
            }
    
            public String getUnivName() {
                return univName;
            }
    
            public void setUnivName(String univName) {
                this.univName = univName;
            }
    
            public String getUnivRank() {
                return univRank;
            }
    
            public void setUnivRank(String univRank) {
                this.univRank = univRank;
            }
    
            public String getUnivScore() {
                return univScore;
            }
    
            public void setUnivScore(String univScore) {
                this.univScore = univScore;
            }
        }
    }
    

   5. 使用Gson解析

  • 定義介面(封裝URL地址和資料請求) :

    @GET("rank_querySpecRankByUniv")
        Call<SpecRankBean> querySpecRankByUnivUseGson(
                @Query("university.univCode") String univCode,
                @Query("page") int page);
    
  • 例項化Retrofit:

    Retrofit retrofit = new Retrofit.Builder()
                     .baseUrl(Constant.BASE_URL)
                     .addConverterFactory(GsonConverterFactory.create())
                     .build();
    
  • 將請求的資料可以直接轉換為我們的Bean,通過各種get方法獲取我們想要的資料:

    call.enqueue(new Callback<SpecRankBean>() {
         @Override
         public void onResponse(Call<SpecRankBean> call, Response<SpecRankBean> response) {
             if(response.isSuccessful()){
                 SpecRankBean bean = response.body();
                 List<SpecRankBean.RowsBean> list = bean.getRows();
                 String result = "";
                 for (SpecRankBean.RowsBean rowsBean : list) {
                     result += rowsBean.getUnivName() + rowsBean.getSpecName() + "\n";
                 }
                 mTextView.setText(result);
             }
         }
    
         @Override
         public void onFailure(Call<SpecRankBean> call, Throwable t) {
    
         }
     });
    

個人公眾號:每日推薦一篇技術部落格,堅持每日進步一丟丟…歡迎關注,想建個微信群,主要討論安卓和Java語言,一起打基礎、用框架、學設計模式,菜雞變菜鳥,菜鳥再起飛,願意一起努力的話可以公眾號留言,謝謝…