欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rxjava 五、简单的网络请求使用

程序员文章站 2022-04-02 18:09:00
...

rxjava+retrofit简单使用

依赖

  implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.x.x'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    // Okhttp库
    implementation 'com.squareup.okhttp3:okhttp:3.1.2'
    // Retrofit库
    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
 public interface TestApi{
        @GET("/")   //使用/或者. 来代替无接口
        Observable<ResponseBody> get();
    }

调用接口

    Gson gson = new GsonBuilder().setLenient().create();
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("https://www.tianqiapi.com/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        TestApi testApi = retrofit.create(TestApi.class);
        testApi.get()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i("zqq","onSubscribe");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Log.i("zqq","responseBody>>"+responseBody.toString());
                        Reader reader = responseBody.charStream();
                        BufferedReader bufferedReader=new BufferedReader(reader);
                        StringBuffer stringBuffer=new StringBuffer();
                        String line="";
                        try {
                            while ((line = bufferedReader.readLine())!=null){
                                stringBuffer.append(line);
                                stringBuffer.append("\r\n");
                            }
                        }catch (Exception e){
                        }

                        Log.i("zqq","responseBody>>"+stringBuffer.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("zqq","onError");
                    }

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

请求结果:
rxjava 五、简单的网络请求使用

相关标签: rxjava