分分钟使用Retrofit+Rxjava实现网络请求

撸代码之前,先简单了解一下为什么Retrofit这么受大家青睐吧。 得意

Retrofit是Square公司出品的基于OkHttp封装的一套RESTful(目前流行的一套api设计的风格)网络请求框架。它内部使用了大量的设计模式,以达到高度解耦的目的;它可以直接通过注解的方式配置请求;可以使用不同的Http客户端;还可以使用json Converter序列化数据,直接转换成你期望生成的实体bean;它还支持Rxjava等等等(此处省略一万字..... 偷笑

好了,接下来开始我们就开始上代码,写个小Demo测试一下它的使用吧!
使用步骤:
1、app的build文件中加入:
 //only Retrofit(只用Retrofit联网)
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
 //Rxjava and Retrofit(Retrofit+Rx需要添加的依赖)
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.2.1'
2、接下来就要编写实现retrofit联网的代码了,以Get请求为例,示例接口:(http://wthrcdn.etouch.cn/weather_mini?city=北京)
首先,你需要创建一个interface用来配置网络请求。
写法《一》:单纯使用Retrofit,不加Rxjava的使用
/**
 * 描述:第一步:定义一个接口配置网络请求
 */
public interface WeatherService {
//  网络接口的使用为查询天气的接口
//  
    @GET("weather_mini")
//  此处回调返回的可为任意类型Call<T>,再也不用自己去解析json数据啦!!!
    Call<WeatherEntity> getMessage(@Query("city") String city);
 在需要请求网络的地方直接调用下面的方法即可:
/**
     * 单纯使用Retrofit的联网请求
     */
    private void doRequestByRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API.BASE_URL)//基础URL 建议以 / 结尾
                .addConverterFactory(GsonConverterFactory.create())//设置 Json 转换器
                .build();
        WeatherService weatherService = retrofit.create(WeatherService .class);
        Call<WeatherEntity> call = weatherService.getMessage("北京");
        call.enqueue(new Callback<WeatherEntity>() {
            @Override
            public void onResponse(Call<WeatherEntity> call, Response<WeatherEntity> response) {
                //测试数据返回
                WeatherEntity weatherEntity = response.body();
                Log.e("TAG", "response == " +  weatherEntity.getData().getGanmao());
            }


            @Override
            public void onFailure(Call<WeatherEntity> call, Throwable t) {
                Log.e("TAG", "Throwable : " + t);
            }
        });
    }
写法《二》 Retrofit + Rxjava
区别:使用Rxjava后,返回的不是Call<T>而是一个Observable<T>的对象了。
public interface RxWeatherService {
    @GET("weather_mini")
    Observable<WeatherEntity> getMessage(@Query("city") String city);
}

请求联网的代码:

请求联网代码:
 private void doRequestByRxRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API.BASE_URL)//基础URL 建议以 / 结尾
                .addConverterFactory(GsonConverterFactory.create())//设置 Json 转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava 适配器
                .build();
        RxWeatherService rxjavaService = retrofit.create(RxWeatherService .class);
        rxjavaService .getMessage("北京")
                .subscribeOn(Schedulers.io())//IO线程加载数据
                .observeOn(AndroidSchedulers.mainThread())//主线程显示数据
                .subscribe(new Subscriber<WeatherEntity>() {
                    @Override
                    public void onCompleted() {


                    }


                    @Override
                    public void onError(Throwable e) {


                    }


                    @Override
                    public void onNext(WeatherEntity weatherEntity) {
                Log.e("TAG", "response == " + weatherEntity.getData().getGanmao());
                    }
                });
    }
免费赠送一个WeatherEntity实体类(只给偷懒的小伙伴):
(在浏览器打开http://wthrcdn.etouch.cn/weather_mini?city=北京,取到json串直接用GsonFormat生成即可)
public class WeatherEntity {
    private DataBean data;
    private int status;
    private String desc;


    public DataBean getData() {
        return data;
    }


    public void setData(DataBean data) {
        this.data = data;
    }


    public int getStatus() {
        return status;
    }


    public void setStatus(int status) {
        this.status = status;
    }


    public String getDesc() {
        return desc;
    }


    public void setDesc(String desc) {
        this.desc = desc;
    }


    public static class DataBean {
        private YesterdayBean yesterday;
        private String city;
        private String aqi;
        private String ganmao;
        private String wendu;
        private List<ForecastBean> forecast;


        public YesterdayBean getYesterday() {
            return yesterday;
        }


        public void setYesterday(YesterdayBean yesterday) {
            this.yesterday = yesterday;
        }


        public String getCity() {
            return city;
        }


        public void setCity(String city) {
            this.city = city;
        }


        public String getAqi() {
            return aqi;
        }


        public void setAqi(String aqi) {
            this.aqi = aqi;
        }


        public String getGanmao() {
            return ganmao;
        }


        public void setGanmao(String ganmao) {
            this.ganmao = ganmao;
        }


        public String getWendu() {
            return wendu;
        }


        public void setWendu(String wendu) {
            this.wendu = wendu;
        }


        public List<ForecastBean> getForecast() {
            return forecast;
        }


        public void setForecast(List<ForecastBean> forecast) {
            this.forecast = forecast;
        }


        public static class YesterdayBean {
   
            private String date;
            private String high;
            private String fx;
            private String low;
            private String fl;
            private String type;


            public String getDate() {
                return date;
            }


            public void setDate(String date) {
                this.date = date;
            }


            public String getHigh() {
                return high;
            }


            public void setHigh(String high) {
                this.high = high;
            }


            public String getFx() {
                return fx;
            }


            public void setFx(String fx) {
                this.fx = fx;
            }


            public String getLow() {
                return low;
            }


            public void setLow(String low) {
                this.low = low;
            }


            public String getFl() {
                return fl;
            }


            public void setFl(String fl) {
                this.fl = fl;
            }


            public String getType() {
                return type;
            }


            public void setType(String type) {
                this.type = type;
            }
        }


        public static class ForecastBean {
  
            private String date;
            private String high;
            private String fengli;
            private String low;
            private String fengxiang;
            private String type;


            public String getDate() {
                return date;
            }


            public void setDate(String date) {
                this.date = date;
            }


            public String getHigh() {
                return high;
            }


            public void setHigh(String high) {
                this.high = high;
            }


            public String getFengli() {
                return fengli;
            }


            public void setFengli(String fengli) {
                this.fengli = fengli;
            }


            public String getLow() {
                return low;
            }


            public void setLow(String low) {
                this.low = low;
            }


            public String getFengxiang() {
                return fengxiang;
            }


            public void setFengxiang(String fengxiang) {
                this.fengxiang = fengxiang;
            }


            public String getType() {
                return type;
            }


            public void setType(String type) {
                this.type = type;
            }
        }
    }
}


好了,简单的Retrofit+Rxjava实现联网到此就完成了。本文主要针对初接触retrofit的开发童鞋,如果对你有所帮助,不要忘了点个赞哦!
后续会更新Retrofit+Rxjava在实际项目开发中的运用,可以直接拿来在项目中使用噢.......敬请期待 再见 再见 再见
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值