Retrofit简单使用四

网络请求地址
http://www.weather.com.cn/adat/sk/101010100.html
retrofit配合Rxjava请求网络。
Rxjava依赖

    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

先上接口类

public interface Api {
   @GET("adat/sk/{cityId}.html")
    Observable getWeatherRxjava(@Path("cityId") String cityId);
}

在使用Gson处理数据时在加了这样一行代码

      .addConverterFactory(GsonConverterFactory.create())

在使用rxjava也要加一行类似代码

  .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

新增的后retrofit的初始化代码

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.weather.com.cn/")
//用来解析数据
                .addConverterFactory(GsonConverterFactory.create())
//用来使用Rxjava
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

请求bean,其实可以在泛型哪里填ResponseBody

public class WeatherJson {
    //weatherinfo需要对应json数据的名称,不然无法解析数据,被坑
    private Weatherinfo weatherinfo;
    public Weatherinfo getWeatherinfo() {
        return weatherinfo;
    }
    public void setWeatherinfo(Weatherinfo weatherinfo) {
        this.weatherinfo = weatherinfo;
    }
    //city、cityid必须对应json数据的名称,不然解析不了
    public class Weatherinfo {
        private String city;
        private String cityid;
        private String temp;
        private String WD;
        private String WS;
        private String SD;
        private String WSE;
        private String time;
        private String isRadar;
        private String Radar;
        private String njd;
        private String qy;
        //省略get和set方法
    }
}

//请求网络数据

Api api = retrofit.create(Api.class);
        Observable observable = api.getWeatherRxjava("101010100");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onError(Throwable e) {
                        Log.i("wxl", "e=" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.i("wxl", "onCompleted");
                    }

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(WeatherJson weatherJson) {
                        Log.i("wxl", "getWeatherinfo=" + weatherJson.getWeatherinfo().getCity());
                    }
                });

你可能感兴趣的:(Retrofit简单使用四)