使用前准备
- 免费的公共接口:查询天气
https://www.apiopen.top/weatherApi?city=临沂
接口返回数据的内容,并做Gson类解析
- 返回内容
{
"code":200,
"msg":"成功!",
"data":{
"yesterday":{
"date":"3日星期日",
"high":"高温 10℃",
"fx":"北风",
"low":"低温 1℃",
"fl":"<![CDATA[<3级]]>",
"type":"小雨"
},
"city":"临沂",
"aqi":null,
"forecast":[
{
"date":"4日星期一",
"high":"高温 9℃",
"fengli":"<![CDATA[<3级]]>",
"low":"低温 0℃",
"fengxiang":"东南风",
"type":"阴"
},
{
"date":"5日星期二",
"high":"高温 14℃",
"fengli":"<![CDATA[<3级]]>",
"low":"低温 1℃",
"fengxiang":"北风",
"type":"阴"
},
{
"date":"6日星期三",
"high":"高温 12℃",
"fengli":"<![CDATA[3-4级]]>",
"low":"低温 3℃",
"fengxiang":"东北风",
"type":"晴"
},
{
"date":"7日星期四",
"high":"高温 11℃",
"fengli":"<![CDATA[<3级]]>",
"low":"低温 0℃",
"fengxiang":"东南风",
"type":"晴"
},
{
"date":"8日星期五",
"high":"高温 11℃",
"fengli":"<![CDATA[<3级]]>",
"low":"低温 0℃",
"fengxiang":"东北风",
"type":"阴"
}
],
"ganmao":"天凉,昼夜温差较大,较易发生感冒,请适当增减衣服,体质较弱的朋友请注意适当防护。",
"wendu":"8"
}
}
- Gson数据解析
public class WeatherInfoModel {
public String code;
@SerializedName("message")
public String message;
@SerializedName("data")
public WeatherInfo weatherInfo;
public class WeatherInfo{
@SerializedName("yesterday")
public DayWeatherInfo yesterdayWeatherInfo;
public String city;
public String aqi;
@SerializedName("forecast")
public List<DayWeatherInfo> forecastWeatherInfo;
@SerializedName("ganmao")
public String hint;
public String wendu;
}
public class DayWeatherInfo{
public String date;
public String high;
public String fx;
public String low;
public String fl;
public String type;
}
@Override
public String toString(){
return "城市: " + weatherInfo.city+", 天气:"+weatherInfo.forecastWeatherInfo.get(0).type+", "+ weatherInfo.forecastWeatherInfo.get(0).high+", "
+ weatherInfo.forecastWeatherInfo.get(0).low+", 提醒:"+weatherInfo.hint;
}
Gson的分析移步Json数据解析-Gson库
创建请求接口
public interface WeatherService {
/**
* 动态指定查询条件
* @Query("字段")
* */
@GET("weatherApi")
Observable<WeatherInfoModel> getWeatherInfo(@Query("city") String city);
}
创建Retrofit并实例化WeatherService
Retrofit retrofit = new Retrofit.Builder().
baseUrl(URL).
addConverterFactory(GsonConverterFactory.create()).
addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
build();
mWeatherService = retrofit.create(WeatherService.class);
通过接口获取Observable并订阅执行
Observable observable = weatherService.getWeatherInfo(city).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
Observer observer = new Observer<WeatherInfoModel>() {
@Override
public void onCompleted() {
LogShowUtil.addLog("Retrofit","结束",true);
}
@Override
public void onError(Throwable e) {
LogShowUtil.addLog("Retrofit","异常",true);
}
@Override
public void onNext(WeatherInfoModel weatherInfoModel) {
LogShowUtil.addLog("Retrofit","当前线程: "+Thread.currentThread().getName(),true);
if (weatherInfoModel.code.equals("200")){
LogShowUtil.addLog("Retrofit",weatherInfoModel.toString(),true);
}else {
LogShowUtil.addLog("Retrofit", "请求失败: " + weatherInfoModel.message,true);
}
}
};
observable.subscribe(observer);