RetroFit与RxJava

依赖:
implementation ‘io.reactivex.rxjava2:rxjava:2.2.6’
implementation ‘io.reactivex.rxjava2:rxandroid:2.1.0’

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
//Gson converter
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

//RxJava2 Adapter
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"

// /http
implementation ‘com.squareup.okhttp3:okhttp:3.4.1’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.9.1’

1:get请求
接口:
public interface Jiekou {

@GET("ios/cf/dish_list.php/")//地址,最好以/结尾

Observable getfood(@Query(“stage_id”)String stage,@Query(“limit”)int limit,@Query(“page”)int page);

}
activity: Retrofit builder = new Retrofit.Builder()
.baseUrl(“http://www.qubaobei.com/”)//同样以/结尾
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();

    Jiekou jiekou = builder.create(Jiekou.class);

    Observable getfood = jiekou.getfood("1", 10, 1);

    getfood.subscribeOn(Schedulers.io())//IO线程加载数据
            .observeOn(AndroidSchedulers.mainThread())//主线程显示数据
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Bean bean) {
                    Toast.makeText(MainActivity.this, "" + bean.getData().toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

2:post请求:

public interface Jiekou {

//方法一
@FormUrlEncoded
@POST(“ios/cf/dish_list.php”)
Observable getjs(@Field(“stage_id”) String stage_id, @Field(“limit”)String limit, @Field(“page”)String page);
//方法二
@POST(“ios/cf/dish_list.php”)
Observable getjs(@Body String str);
}
activity: Retrofit builder = new Retrofit.Builder()
.baseUrl(“http://www.qubaobei.com/”)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();

    Jiekou jiekou = builder.create(Jiekou.class);

    Observable getfood = jiekou.getpost("1", 10, 1);

    getfood.subscribeOn(Schedulers.io())//IO线程加载数据
            .observeOn(AndroidSchedulers.mainThread())//主线程显示数据
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Bean bean) {
                    Toast.makeText(MainActivity.this, "" + bean.getData().toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

你可能感兴趣的:(RetroFit与RxJava)