Retrofit2.0使用小结

Retrofit2.0都说是网络请求神器,我也来使用使用,大家有什么好的想法也可以和我讨论讨论。

依赖库配置

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.okhttp:okhttp:2.7.5'  

第一个是retrofit的库,第二个是使用GSON解析必须依赖的,第三个是GSON的库,第四个是okhttp的库。

数据类型

我用的数据是聚合的周公解梦的数据:

{
    "reason": "successed",
    "result": [
        {
            "id": "89",/*类别id*/
            "name": "其它动物", /*类别名称*/
            "fid": "3"/*所属父类ID,0为顶级分类*/
        },
        {
            "id": "85",
            "name": "哺乳类",
            "fid": "3"
        },
        {
            "id": "86",
            "name": "昆虫类",
            "fid": "3"
        },
        {
            "id": "87",
            "name": "冷血类",
            "fid": "3"
        },
        {
            "id": "88",
            "name": "鸟禽类",
            "fid": "3"
        }
    ],
    "error_code": 0/*返回码*/
}

因为用到了GSON,所以定义了2个BEAN:
Bean:


import java.util.List;

/**
 * Created by wxy on 2016-07-22.
 */
public class Bean {
    String reason;
    String error_code;
    List<ListBean> result;

    @Override
    public String toString() {
        return "Bean{" +
                "reason='" + reason + '\'' +
                ", error_code='" + error_code + '\'' +
                ", result=" + result +
                '}';
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public void setError_code(String error_code) {
        this.error_code = error_code;
    }

    public void setResult(List<ListBean> result) {
        this.result = result;
    }

    public String getReason() {
        return reason;
    }

    public String getError_code() {
        return error_code;
    }

    public List<ListBean> getResult() {
        return result;
    }
}

ListBean:


/**
 * Created by wxy on 2016-07-22.
 */
public class ListBean {
    String id;
    String name;
    String fid;

    @Override
    public String toString() {
        return "ListBean{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", fid='" + fid + '\'' +
                '}';
    }

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

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

    public void setFid(String fid) {
        this.fid = fid;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getFid() {
        return fid;
    }
}

使用retrofit

基础retrofit使用:

根据retrofit官网的意思,我们在使用retrofit时必须先创建一个java接口来存储我们的HTTP API:

import retrofit2.Call;
import retrofit2.http.GET;

/**
 * Created by wxy on 2016-07-22.
 */
public interface MyEndpointInterface {
    //这是一个get方法,返回的数据类型是Bean对象
    @GET("/dream/category?key=62236e47e54c0fb9cf7fba94210298eb")
    Call<ZgBean> getData();
}

retrofit的配置:

public static final String BASE_URL = "http://v.juhe.cn";
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

MyEndpointInterface myEndpointInterface = retrofit.create(MyEndpointInterface.class);

通过baseUrl和接口中的get中的URL拼接以后成为了我们最终的get的URL,这里有好多种方式可以进行url的拼接。
如果要用GSON必须添加addConverterFactory(GsonConverterFactory.create());
我这里是异步获取数据所以使用的是:

 myEndpointInterface.getData().enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                Log.e("TAG", "Response:" + response.body().toString());
                if (response.body().getResult() == null) {
                    Log.e("TAG", "listdata为空");
                } else {
                    Log.e("TAG", "listdata中有数据");
                }
            }
            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
                Log.e("TAG", "error:" + t.getMessage());
            }
        });

最后我们就能获取到我们的json数据了:

Response:Bean
{reason='successed', 
error_code='0', 
result=[ListBean{id='1', name='人物类', fid='0'}, ListBean{id='2', name='其他类', fid='0'}, ListBean{id='3', name='动物类', fid='0'}, ListBean{id='4', name='娱乐类', fid='0'}, ListBean{id='5', name='宗教类', fid='0'}, ListBean{id='6', name='山水类', fid='0'}, ListBean{id='7', name='建筑类', fid='0'}, ListBean{id='8', name='恐怖类', fid='0'}, ListBean{id='9', name='情爱类', fid='0'}, ListBean{id='10', name='植物类', fid='0'}, ListBean{id='11', name='活动类', fid='0'}, ListBean{id='12', name='物品类', fid='0'}, ListBean{id='13', name='生活类', fid='0'}, ListBean{id='14', name='疾病类', fid='0'}, ListBean{id='15', name='自然类', fid='0'}, ListBean{id='16', name='身体类', fid='0'}, ListBean{id='17', name='运动类', fid='0'}, ListBean{id='18', name='食物类', fid='0'}, ListBean{id='19', name='鬼神类', fid='0'}, ListBean{id='85', name='哺乳类', fid='3'}, ListBean{id='86', name='昆虫类', fid='3'}, ListBean{id='87', name='冷血类', fid='3'}, ListBean{id='88', name='鸟禽类', fid='3'}, ListBean{id='89', name='其它动物', fid='3'}, ListBean{id='90', name='鬼怪类', fid='19'}, ListBean{id='91', name='其它鬼神', fid='19'}, ListBean{id='92', name='神仙类', fid='19'}, ListBean{id='93', name='动作类', fid='11'}, ListBean{id='94', name='工作学习', fid='11'}, ListBean{id='95', name='劳动类', fid='11'}, ListBean{id='96', name='其它活动', fid='11'}, ListBean{id='97', name='日常类', fid='11'}, ListBean{id='98', name='医疗疾病', fid='14'}, ListBean{id='99', name='场所类', fid='7'}, ListBean{id='100', name='建筑类', fid='7'}, ListBean{id='101', name='灾难罪恶', fid='8'}, ListBean{id='102', name='其它', fid='2'}, ListBean{id='103', name='时间节日', fid='2'}, ListBean{id='104', name='数字形状', fid='2'}, ListBean{id='105', name='颜色气味', fid='2'}, ListBean{id='106', name='婚恋情感', fid='9'}, ListBean{id='107', name='人物称谓', fid='1'}, ListBean{id='108', name='地理环境', fid='6'}, ListBean{id='109', name='身体器官', fid='16'}, ListBean{id='110', name='感觉表情', fid='13'}, ListBean{id='111', name='其它生活', fid='13'}, ListBean{id='112', name='衣食住行', fid='13'}, ListBean{id='113', name='食品饮料', fid='18'}, ListBean{id='114', name='财物宝石', fid='12'}, ListBean{id='115', name='服装饰品', fid='12'}, ListBean{id='116', name='机械电器', fid='12'}, ListBean{id='117', name='交通运输', fid='12'}, ListBean{id='118', name='其它物品', fid='12'}, ListBean{id='119', name='生活用品', fid='12'}, ListBean{id='120', name='文化用品', fid='12'}, ListBean{id='121', name='武器化学', fid='12'}, ListBean{id='122', name='音乐舞蹈', fid='12'}, ListBean{id='123', name='娱乐类', fid='4'}, ListBean{id='124', name='运动类', fid='17'}, ListBean{id='125', name='豆类', fid='10'}, ListBean{id='126', name='瓜类', fid='10'}, ListBean{id='127', name='果实', fid='10'}, ListBean{id='128', name='花草', fid='10'}, ListBean{id='129', name='粮食', fid='10'}, ListBean{id='130', name='其它植物', fid='10'}, ListBean{id='131', name='蔬菜', fid='10'}, ListBean{id='132', name='树类', fid='10'}, ListBean{id='133', name='自然现象', fid='15'}, ListBean{id='134', name='宗教类', fid='5'}]}

优化方案:

既然基础的retrofit能用了,那么每次要用,都需要去写retrofit的配置,肯定非常的繁琐,所以我们需要进行一点点的封装,不会偷懒的程序猿不是好的程序猿。
我们可以把retrofit的配置分出来,单独创建到一个类里面:

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wxy on 2016-07-22.
 */
public class MyHttpHelp {
    public static MyEndpointInterface myEndpointInterface;
    public static Retrofit retrofit = null;

    public static MyEndpointInterface getInstence(String BASE_URL) {
        if (myEndpointInterface == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            myEndpointInterface = retrofit.create(MyEndpointInterface.class);
        }
        return myEndpointInterface;
    }
}

这样我们就不需要每次都去创建retrofit对象和实例我们的接口了,我们以后只要在需要使用的地方直接这样调用就可以了:

 MyHttpHelp.getInstence().getData().enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                Log.e("TAG", "Response:" + response.body().toString());
                if (response.body().getResult() == null) {
                    Log.e("TAG", "listdata为空");
                } else {
                    Log.e("TAG", "listdata中有数据");
                }
            }
            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
                Log.e("TAG", "error:" + t.getMessage());
            }
        });

这样就方便很多,如果需要增加新的请求地址,我们只需要在接口类里面新写一个,比如:

import retrofit2.Call;
import retrofit2.http.GET;

/**
 * Created by wxy on 2016-07-22.
 */
public interface MyEndpointInterface {
    //这是一个get方法,返回的数据类型是Bean对象
    @GET("dream/category?key=62236e47e54c0fb9cf7fba94210298eb")
    Call<Bean> getData();

    //这是一个新的get方法,返回的也是Bean对象
    @GET("dream/category?key=62236e47e54c0fb9cf7fba94210298eb")
    Call<Bean> getData2();
}

然后在只要MyHttpHelp.getInstence().getData2(),就能获取到相应的新的数据了。retrofit的使用非常方便,我也是刚刚开始接触,有许多不清楚的,如果其中有错的地方,还请大家多多包涵,可以多多指教指教。
最后,多谢StormZhang的鼓励,还有多谢泡在网上的日子的retrofit的文章。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值