教你分分钟使用Retrofit+Rxjava实现网络请求
擼代碼之前,先簡(jiǎn)單了解一下為什么Retrofit這么受大家青睞吧。
Retrofit是Square公司出品的基于OkHttp封裝的一套R(shí)ESTful(目前流行的一套api設(shè)計(jì)的風(fēng)格)網(wǎng)絡(luò)請(qǐng)求框架。它內(nèi)部使用了大量的設(shè)計(jì)模式,以達(dá)到高度解耦的目的;它可以直接通過(guò)注解的方式配置請(qǐng)求;可以使用不同的Http客戶(hù)端;還可以使用json Converter序列化數(shù)據(jù),直接轉(zhuǎn)換成你期望生成的實(shí)體bean;它還支持Rxjava等等等(此處省略一萬(wàn)字...........)
好了,接下來(lái)開(kāi)始我們就開(kāi)始上代碼,寫(xiě)個(gè)小Demo測(cè)試一下它的使用吧! 使用步驟: 1、app的build文件中加入:
//only Retrofit(只用Retrofit聯(lián)網(wǎng))compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0' //Rxjava and Retrofit(Retrofit+Rx需要添加的依賴(lài))compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'compile 'io.reactivex:rxandroid:1.2.1'compile 'io.reactivex:rxjava:1.2.1' 復(fù)制代碼2、接下來(lái)就要編寫(xiě)實(shí)現(xiàn)retrofit聯(lián)網(wǎng)的代碼了,以Get請(qǐng)求為例,示例接口:(http://wthrcdn.etouch.cn/weather_mini?city=北京) 首先,你需要?jiǎng)?chuàng)建一個(gè)interface用來(lái)配置網(wǎng)絡(luò)請(qǐng)求。 寫(xiě)法《一》:單純使用Retrofit,不加Rxjava的使用
/** * 描述:第一步:定義一個(gè)接口配置網(wǎng)絡(luò)請(qǐng)求 */ public interface WeatherService { // 網(wǎng)絡(luò)接口的使用為查詢(xún)天氣的接口 // @GET("weather_mini") // 此處回調(diào)返回的可為任意類(lèi)型Call<T>,再也不用自己去解析json數(shù)據(jù)啦!!!Call<WeatherEntity> getMessage(@Query("city") String city); 復(fù)制代碼在需要請(qǐng)求網(wǎng)絡(luò)的地方直接調(diào)用下面的方法即可:
/*** 單純使用Retrofit的聯(lián)網(wǎng)請(qǐng)求*/private void doRequestByRetrofit() {Retrofit retrofit = new Retrofit.Builder().baseUrl(API.BASE_URL)//基礎(chǔ)URL 建議以 / 結(jié)尾.addConverterFactory(GsonConverterFactory.create())//設(shè)置 Json 轉(zhuǎn)換器.build();WeatherService weatherService = retrofit.create(WeatherService .class);Call<WeatherEntity> call = weatherService.getMessage("北京");call.enqueue(new Callback<WeatherEntity>() {@Overridepublic void onResponse(Call<WeatherEntity> call, Response<WeatherEntity> response) {//測(cè)試數(shù)據(jù)返回WeatherEntity weatherEntity = response.body();Log.e("TAG", "response == " + weatherEntity.getData().getGanmao());}@Overridepublic void onFailure(Call<WeatherEntity> call, Throwable t) {Log.e("TAG", "Throwable : " + t);}});}復(fù)制代碼寫(xiě)法《二》 Retrofit + Rxjava 區(qū)別:使用Rxjava后,返回的不是Call而是一個(gè)Observable的對(duì)象了。
public interface RxWeatherService {@GET("weather_mini")Observable<WeatherEntity> getMessage(@Query("city") String city); } 復(fù)制代碼請(qǐng)求聯(lián)網(wǎng)代碼:
private void doRequestByRxRetrofit() {Retrofit retrofit = new Retrofit.Builder().baseUrl(API.BASE_URL)//基礎(chǔ)URL 建議以 / 結(jié)尾.addConverterFactory(GsonConverterFactory.create())//設(shè)置 Json 轉(zhuǎn)換器.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava 適配器.build();RxWeatherService rxjavaService = retrofit.create(RxWeatherService .class);rxjavaService .getMessage("北京").subscribeOn(Schedulers.io())//IO線程加載數(shù)據(jù).observeOn(AndroidSchedulers.mainThread())//主線程顯示數(shù)據(jù).subscribe(new Subscriber<WeatherEntity>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {}@Overridepublic void onNext(WeatherEntity weatherEntity) {Log.e("TAG", "response == " + weatherEntity.getData().getGanmao());}});} 復(fù)制代碼免費(fèi)贈(zèng)送一個(gè)WeatherEntity實(shí)體類(lèi)(只給偷懶的小伙伴): (在瀏覽器打開(kāi)http://wthrcdn.etouch.cn/weather_mini?city=北京,取到j(luò)son串直接用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;}}} }復(fù)制代碼好了,簡(jiǎn)單的Retrofit+Rxjava實(shí)現(xiàn)聯(lián)網(wǎng)到此就完成了。本文主要針對(duì)初接觸retrofit的開(kāi)發(fā)童鞋,如果對(duì)你有所幫助,不要忘了點(diǎn)個(gè)贊哦! 后續(xù)會(huì)更新Retrofit+Rxjava在實(shí)際項(xiàng)目開(kāi)發(fā)中的運(yùn)用,可以直接拿來(lái)在項(xiàng)目中使用噢.......敬請(qǐng)期待??????
總結(jié)
以上是生活随笔為你收集整理的教你分分钟使用Retrofit+Rxjava实现网络请求的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 做梦梦到仙家的旗预示什么
- 下一篇: 做梦梦到洗澡什么意思