美文网首页
Android Rxjava+Retrofit 网络数据请求

Android Rxjava+Retrofit 网络数据请求

作者: Janice_x | 来源:发表于2021-01-09 18:01 被阅读0次

    1、添加依赖

    //retrofit网络请求框架
      implementation 'com.squareup.retrofit2:retrofit:2.5.0'
      //retrofit添加Json解析返回数据
      implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
      //retrofit添加Rxjava支持
      implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
      //rxjava框架
      implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
    

    2、创建 RetrofitFactory (单例模式)

    • 创建 OkHttpClient
    mOkHttpClient = new OkHttpClient().newBuilder()
            .readTimeout(mTimeOut, TimeUnit.SECONDS)
            .callTimeout(mTimeOut,TimeUnit.SECONDS)
            .writeTimeout(mTimeOut,TimeUnit.SECONDS)
            .addInterceptor(new URLInterceptor())//添加过滤器
            .retryOnConnectionFailure(true)//设置出现错误进行重新连接
        .build();
    

    addInterceptor 添加过滤器,可根据需要进行过滤数据

    public static class URLInterceptor implements Interceptor {
        private String TAG = "okhttp";
    
        @Override
        public Response intercept(Chain chain) throws IOException {
          Request request = chain.request()
                              .newBuilder()
                              .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")//添加请求头
              //                .addHeader("Accept-Encoding", "gzip, deflate")
              //                .addHeader("Connection", "keep-alive")
              //                .addHeader("Accept", "*/*")
              //                .addHeader("Cookie", "add cookies here")
                              .build()
              ;
    
          Log.e(TAG,"request:" + request.toString());
          long t1 = System.nanoTime();
          okhttp3.Response response = chain.proceed(chain.request());
          long t2 = System.nanoTime();
          Log.e(TAG,String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
              response.request().url(), (t2 - t1) / 1e6d, response.headers()));
          okhttp3.MediaType mediaType = response.body().contentType();
          String content = response.body().string();
          Log.e(TAG, "response body:" + content);
          return response.newBuilder()
              .body(okhttp3.ResponseBody.create(mediaType, content))
              //                .header("Authorization", Your.sToken)
              .build();
          //return chain.proceed(request);
        }
    
    • 创建Retrofit
    public <T> T getService(Class<T> serviceClass) {
        if(mRetrofit == null ){
          mRetrofit = new Retrofit.Builder()
              .baseUrl(BASEURLS_DOMAIN)//添加域名
              .client(mOkHttpClient) // 添加mOkHttpClient
              .addConverterFactory(GsonConverterFactory.create())//
              .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
              .build();
        }
        return mRetrofit.create(serviceClass);
      }  
    

    https://ke.4399tech.com/ 本次实战项目的域名

    3、封装BaseResponse与BaseObserver的封装

    BaseResponse是个人自定义命名的一个类,主要用来对返回数据进行抽象。

    BaseObserver是对返回数据的基础数据部分进行统一处理。

    /**
     * 创建Base抽象类实现Observer
     */
    public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
        private static final String TAG = "BaseObserver";
        @Override
        public void onSubscribe(Disposable d) {
            Log.e(TAG, "onSubscribe: " );
        }
        @Override
        public void onNext(BaseResponse<T> response) {
            //在这边对 基础数据 进行统一处理  举个例子:
            if(response.getRes_code()==200){
                onSuccess(response.getResult());
            }else{
                onSuccess(null,response.getErr_msg(),response.getCode());
            }
        }
        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "Throwable: " + e.getMessage());
               public abstract void onFailure(Throwable e, e.getMessage());
        }
    
        @Override
        public void onComplete() {
            Log.e(TAG, "onComplete: " );
        }
    
        public abstract void onSuccess(T demo);
        public abstract void onSuccess(T demo, String  errorMsg, int code);
        public abstract void onFailure(Throwable e,String errorMsg);
    

    4、根据需求创建请求接口

    @GET("/api/apiIndex/getGoodsList")
      Observable<BaseResponse<List<GoodsInfo>>> getGoodsList();
    
      //https://blog.csdn.net/jing_80/article/details/82931626
      @Multipart
      @POST("/api/apiuser/login")
      Observable<BaseResponse<String>> loginIn(@PartMap Map<String, RequestBody> requestBodyMap);
    

    请求类型 @GET @POST

    5、请求网络数据

    RetrofitFactory.getInstance().getService(ApiUrl.class)
                    .getRetrofit2()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<Demo>(){
                        @Override
                        public void onSuccess(Demo demo) {
                            Log.e(TAG, "onSuccess: "+demo);
                        }
                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            Log.e(TAG, "onFailure: "+errorMsg);
                        }
                    });
    

    相关文章

      网友评论

          本文标题:Android Rxjava+Retrofit 网络数据请求

          本文链接:https://www.haomeiwen.com/subject/ozecaktx.html