參考https://www.jianshu.com/p/6922337b4f88
感謝作者的無私奉獻
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);
}
請求聯網代碼:
在AndroidManifest.xml添加網絡權限
<uses-permission android:name="android.permission.INTERNET"/>
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;
}
}
}
}
GsnFormat的依賴:
1.點擊file->setting->plugins
搜索GsonFormat ->點擊install ->重啓studio即可
2.此處將自己初步是用時的一些注意事項以及自己所爬的坑稍作記錄:
a.在書寫RxWeatherService時對其中的Observable導包不正確,引起了各種的坑
正確的導包是