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

参考博客:

  • Retrofit2使用(非常简洁易懂)

实现效果:

      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

  • 所用api:http://www.mrsorrow.xin/pro/rank_querySpecRankByUniv?university.univCode=10280&page=1
  • 功能:根据高校代码进行学科专业类排名
  • 返回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 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 call = service.querySpecRankByUniv("10280", 1);
     call.enqueue(new Callback() {
         @Override
         public void onResponse(Call call, Response response) {
             if(response.isSuccessful()){
                 try {
                     String result = response.body().string();
                     mTextView.setText(result);
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
    
         @Override
         public void onFailure(Call 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 rows;
    
        public List getRows() {
            return rows;
        }
    
        public void setRows(List 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 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() {
         @Override
         public void onResponse(Call call, Response response) {
             if(response.isSuccessful()){
                 SpecRankBean bean = response.body();
                 List list = bean.getRows();
                 String result = "";
                 for (SpecRankBean.RowsBean rowsBean : list) {
                     result += rowsBean.getUnivName() + rowsBean.getSpecName() + "\n";
                 }
                 mTextView.setText(result);
             }
         }
    
         @Override
         public void onFailure(Call call, Throwable t) {
    
         }
     });
    



个人公众号:每日推荐一篇技术博客,坚持每日进步一丢丢…欢迎关注,想建个微信群,主要讨论安卓和Java语言,一起打基础、用框架、学设计模式,菜鸡变菜鸟,菜鸟再起飞,愿意一起努力的话可以公众号留言,谢谢…

你可能感兴趣的:(Android,Android框架之路)