Rxjava2+Retrofit2结合mvp的简单教程Retrofit篇(二):Retrofit的简单封装


既然说到封装,那就是对请求和返回结果进行统一处理

  • 1 还是之前的post请求,我把返回结果写到ResultEntity这个类里面
public class ResultEntity<T> {
    /**
     *    服务器返回数据一般就是{"code":0, "message":"123", "data:":泛型}
     *   但是我们这边是测试,返回的数据格式如下,所以我们的结果处理只需要对info做处理就行
     *
     {"info": [{
     "id": "5718",
     "name": "\u300a\u5200\u950b\u4e4b\u5203\u300b\u5f00\u6d4b\u793c\u5305",
     "gamename": "\u5200\u950b\u4e4b\u5203",
     "icon": "http:\/\/i5.72g.com\/upload\/201606\/201606081043002654.jpg",
     "remain": "48",
     "gifttype": "1",
     "consume": "0",
     "content": "\u91d1\u5e01*10W\uff0c\u7fbd\u7075\u4e4b\u5fc3*500\uff0c\u9501\u8fb9\u7b26*2"
     },
     {
     "id": "6686",
     "name": "\u822a\u6d77\u738b\u542f\u822a\u6691\u671f\u793c\u5305",
     "gamename": "\u822a\u6d77\u738b\u542f\u822a",
     "icon": "http:\/\/i3.72g.com\/upload\/201606\/201606240949087788.jpg",
     "remain": "3",
     "gifttype": "1",
     "consume": "0",
     "content": "\u4ee5\u4e0b\u793c\u5305\u968f\u673a\u53d1\u653e\u4e00\u4e2a\uff1a\n1\uff1a100\u94bb \uff0c\u6d77\u76d7\u4fbf\u5f53*2 \uff0c\u5927\u94b1\u888b*2 \uff0c\u6676\u77f3\u5927\u793c\u5305*2 \uff0c\u8d85\u7ea7\u7ecf\u9a8c\u836f\u6c34*2\n2\uff1a\u94bb*188 \uff0c\u6d77\u76d7\u4fbf\u5f53*5 \uff0c\u5927\u94b1\u888b*5 \uff0c\u6676\u77f3\u5927\u793c\u5305*5 \uff0c\u8d85\u7ea7\u7ecf\u9a8c\u836f\u6c34*5\n3\uff1a\u8def\u98de\u788e\u7247*10 \uff0c\u94bb*88 \uff0c\u6d77\u76d7\u4fbf\u5f53*1 \uff0c\u5927\u94b1\u888b*1 \uff0c\u6676\u77f3\u5927\u793c\u5305*1\n4\uff1a\u94bb*188 \uff0c\u6d77\u76d7\u4fbf\u5f53*5 \uff0c\u5927\u94b1\u888b*5 \uff0c\u6676\u77f3\u5927\u793c\u5305*5 \uff0c\u8d85\u7ea7\u7ecf\u9a8c\u836f\u6c34*5\n5\uff1a100\u94bb \uff0c\u6d77\u76d7\u4fbf\u5f53*2 \uff0c\u5927\u94b1\u888b*2 \uff0c\u6676\u77f3\u5927\u793c\u5305*2 \uff0c\u8d85\u7ea7\u7ecf\u9a8c\u836f\u6c34*2\n6\uff1a\u94bb*188 \uff0c\u6d77\u76d7\u4fbf\u5f53*5 \uff0c\u5927\u94b1\u888b*5 \uff0c\u6676\u77f3\u5927\u793c\u5305*5 \uff0c\u8d85\u7ea7\u7ecf\u9a8c\u836f\u6c34*5\n7\uff1a\u8def\u98de\u788e\u7247*10 \uff0c\u94bb*88 \uff0c\u6d77\u76d7\u4fbf\u5f53*1 \uff0c\u5927\u94b1\u888b*1 \uff0c\u6676\u77f3\u5927\u793c\u5305*1"
     }]}
     */
//    private int code;
//    private String message;
    private T info;

    public T getInfo() {
        return info;
    }

    public void setInfo(T info) {
        this.info = info;
    }
}

因为返回的是一个数组,我们把数组中的单个提取到一个bean类里面,我命名为GameBean,代码如下:

public class GameBean implements Serializable{

        /**
         * id : 5718
         * name : 《刀锋之刃》开测礼包
         * gamename : 刀锋之刃
         * icon : http://i5.72g.com/upload/201606/201606081043002654.jpg
         * remain : 48
         * gifttype : 1
         * consume : 0
         * content : 金币*10W,羽灵之心*500,锁边符*2
         */

        private String id;
        private String name;
        private String gamename;
        private String icon;
        private String remain;
        private String gifttype;
        private String consume;
        private String content;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGamename() {
            return gamename;
        }

        public void setGamename(String gamename) {
            this.gamename = gamename;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public String getRemain() {
            return remain;
        }

        public void setRemain(String remain) {
            this.remain = remain;
        }

        public String getGifttype() {
            return gifttype;
        }

        public void setGifttype(String gifttype) {
            this.gifttype = gifttype;
        }

        public String getConsume() {
            return consume;
        }

        public void setConsume(String consume) {
            this.consume = consume;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

}
  • 2 去修改RetrofitService类getGameList方法,第一把返回结果改为List<GameBean>,第二我们参数改为map(这个看个人爱好,你还可以接着用上篇中的RequestBody ):
public interface RetrofitService {
    @FormUrlEncoded
    @POST("app/gift/gift_list/")
    Call<ResultEntity<List<GameBean>>> getGameList(@FieldMap Map<String, String> map);
}
  • 3 返回结果要从ResponseBody转化为Bean,需要添加gson转换器,在gradle下面添加compile 'com.squareup.retrofit2:converter-gson:2.3.0',然后在初始化retrofit的时候添加一行代码,这样retrofit就可以把数据自动给转换为bean类了
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .build();
  • 4 下面我们建一个ResponseCallback类对结果进行集中处理
public  class ResponseCallback<T> {
    private Call<ResultEntity<T>> mCall;//拿到所有的call请求,集中处理
    //返回结果处理后通过接口传给需要结果显示的地方,一般是activity,在activity中实现这个接口
    public interface ResponseListener<T> {
        void onSuccess(T t);
        void onFail(String error);
    }
    public ResponseCallback(Call call) {
        mCall = call;
    }
    //对结果进行处理,说明一下在这里与okhttp不同的地方时,callback是在主线程直接可以更新ui,而okhttp则是工作线程需要通过handler等把结果传给主线程
    public void handleResponse(final ResponseListener listener) {
        mCall.enqueue(new Callback<ResultEntity<T>>() {
            @Override
            public void onResponse(Call<ResultEntity<T>> call, Response<ResultEntity<T>> response) {
                if (response.isSuccessful() && response.errorBody() == null) {
                    listener.onSuccess((T) response.body().getInfo());
                }
            }

            @Override
            public void onFailure(Call<ResultEntity<T>> call, Throwable t) {
                listener.onFail(t.getMessage().toString());
            }
        });
    }
    }
  • 5 最后看一下activity中的调用代码
public class RetrofitActivity extends AppCompatActivity {
    private String TAG = "RetrofitActivity";
    private TextView tvResult;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.retrofit);
        tvResult= (TextView) findViewById(R.id.tv_result);
        //POST请求和上篇一样,创建请求体
        try {
           final Map<String, String> map = new HashMap<String, String>();
            map.put("page", "1");
            map.put("code", "news");
            map.put("pageSize", "20");
            map.put("parentid", "0");
            map.put("type", "1");
            Call<ResultEntity<List<GameBean>>> call= HttpCenter.getInstance().service.getGameList(map);
            new ResponseCallback<List<GameBean>>(call).handleResponse(new ResponseCallback.ResponseListener<List<GameBean>>() {
                @Override
                public void onSuccess(List<GameBean> gameBeens) {
                    if(gameBeens!=null&&gameBeens.size()>0)
                    tvResult.setText(gameBeens.get(0).toString());//textview显示请求结果
                }

                @Override
                public void onFail(String error) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

其中HttpCenter类是将retrofit封装成单例,代码如下

public class HttpCenter {
    public RetrofitService service;
    public static final String BASE_URL = "http://zhushou.72g.com/";//BASE_URL请以/结尾
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public ResponseCallback responseCallback;

    private static class HttpCenterHolder {
        private static final HttpCenter INSTANCE = new HttpCenter();
    }

    public static final HttpCenter getInstance() {
        return HttpCenterHolder.INSTANCE;
    }

    private HttpCenter() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .build();
        service = retrofit.create(RetrofitService.class);
    }
}

运行结果如下图:

运行结果

所有代码均已上传到github:https://github.com/MrAllRight/HttpExample
本位参考: http://blog.csdn.net/gesanri/article/details/50938275

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容