知识技术介绍|Retrofit2和Rxjava2和LiveData的请求整理

【知识技术介绍|Retrofit2和Rxjava2和LiveData的请求整理】Retrofit是Square公司出品的基于OkHttp封装的一套RESTful(目前流行的一套api设计的风格)网络请求框架。它内部使用了大量的设计模式,以达到高度解耦的目的;它可以直接通过注解的方式配置请求;可以使用不同的Http客户端;还可以使用json Converter序列化数据,直接转换成你期望生成的实体bean;它还支持Rxjava和LiveData等等等
Rxjava2和LiveData是利用Retrofit2的使用来返回独立的对象处理

LiveData + ViewModel替代Rxjava2,但缺少一些Rxjava2没有的功能,如Stream,Rxjava2中缺少关于LiveData中
LiveData 算是一个数据持久类
Rxjava2 有链式响应请求的过程
组合方式
1、Retrofit 单独请求
2、Retrofit+RxJava实现网络请求,返回的是Observable
3、Retrofit+LiveData实现网络请求,返回的是LiveData
以上请求加上OkHttpClient,可以进行请求拦截处理和超时等设置(超时时间设置生不生效不好说)
Retrofit的创建方式一样,只是ApiService中接口返回不一样
基本形式

Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://fanyi.youdao.com/") //设置网络请求的Url地址 .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();

返回形式:
@GET("xxxxx") Call getDataBeanObservable(); @GET("xxxxx") LiveData getDataBeanLiveData(); @GET("xxxxx") Observable getDataBeanObservable();

Retrofit + LiveData
RetrofitManager.get("https://cn.bing.com/") .create(SplashService.class) .getBingImgLiveData().observe(this, new Observer() { @Override public void onChanged(BingImg bingImg) { Log.d(TAG, "onChanged: 请求结果:"+new Gson().toJson(bingImg)); } });

Retrofit请求分为同步请求和异步请求
写法《一》:单纯使用Retrofit,不加Rxjava的使用
/** * 描述:第一步:定义一个接口配置网络请求 */ public interface WeatherService { //网络接口的使用为查询天气的接口 // @GET("weather_mini") //此处回调返回的可为任意类型Call,再也不用自己去解析json数据啦!!! Call 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 call = weatherService.getMessage("北京"); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { //测试数据返回 WeatherEntity weatherEntity = response.body(); Log.e("TAG", "response == " +weatherEntity.getData().getGanmao()); }@Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "Throwable : " + t); } }); //同步请求 try { Response response = call.execute(); response.body().show(); } catch (IOException e) { e.printStackTrace(); } }

写法《二》 Retrofit + Rxjava
区别:使用Rxjava后,返回的不是Call而是一个Observable的对象了。
public interface RxWeatherService { @GET("weather_mini") Observable 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() { @Override public void onCompleted() {}@Override public void onError(Throwable e) {}@Override public void onNext(WeatherEntity weatherEntity) { Log.e("TAG", "response == " + weatherEntity.getData().getGanmao()); } }); }

免费赠送一个WeatherEntity实体类(只给偷懒的小伙伴):
public class WeatherEntity { private DataBean data; private int status; private String desc; public DataBean getData() { return data; }public void setData(DataBean data) { this.data = https://www.it610.com/article/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 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 getForecast() { return forecast; }public void setForecast(List 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; } } } }


    推荐阅读