擼代碼之前,先簡單了解一下為什么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>() {@Overridepublic void onResponse(Call<WeatherEntity> call, Response<WeatherEntity> response) {//測試數據返回WeatherEntity weatherEntity = response.body();Log.e("TAG", "response == " + weatherEntity.getData().getGanmao());}@Overridepublic void onFailure(Call<WeatherEntity> call, Throwable t) {Log.e("TAG", "Throwable : " + t);}});}復制代碼
寫法《二》 Retrofit + Rxjava 區別:使用Rxjava后,返回的不是Call而是一個Observable的對象了。
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>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {}@Overridepublic 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在實際項目開發中的運用,可以直接拿來在項目中使用噢.......敬請期待??????