擼程式碼之前,先簡單瞭解一下為什麼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而是一個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>() {
@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在實際專案開發中的運用,可以直接拿來在專案中使用噢.......敬請期待??????