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

Rxjava+Retrofit+Okhttp进行嵌套网络

程序员文章站 2022-06-03 23:05:39
...
  1. OK网络框架拦截器以及拦截器依赖:
    implementation ‘com.squareup.okhttp3:logging-interceptor:3.12.0’
    implementation ‘com.squareup.okhttp3:okhttp:3.12.0’
    这是Retrofit+RxJava+Rxandroid:
    implementation ‘com.squareup.retrofit2:retrofit:2.6.0’
    implementation ‘io.reactivex:rxjava:1.3.8’
    implementation ‘io.reactivex:rxandroid:1.2.1’
    implementation ‘com.squareup.retrofit2:adapter-rxjava:2.6.0’
    implementation ‘com.squareup.retrofit2:converter-gson:2.6.0’
    implementation ‘com.squareup.retrofit2:retrofit:2.0.2’ 第一步:需要自定义拦截
    简介:
    这是是通过登录-----到同步添加数据—再到展示数据购物车一个嵌套
    **//①获取请求的方法要写在静态单列模式 **
    private final RequestMethod mRequestMethod;/这是变量
    private MyBaseUtils() {
    //这里是依赖拦截日志
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS)
    .connectTimeout(10, TimeUnit.SECONDS)
    .addInterceptor(loggingInterceptor)
    .addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
    SharedPreferences lvxx = MyApp.mContext.getSharedPreferences(“lvxx”, Context.MODE_PRIVATE);
    String userId = lvxx.getString(“userId”, null);
    String sessionId = lvxx.getString(“sessionId”, null);
    if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(sessionId)){
    return chain.proceed(chain.request());
    }else {
    Request request = chain.request().newBuilder()
    .addHeader(“userId”, userId)
    .addHeader(“sessionId”, sessionId)
    .build();
    return chain.proceed(request);
    }
    }
    })
    .build();
    Retrofit retrofit = new Retrofit.Builder().client(okHttpClient)
    .baseUrl(MyUrl.BASE_URL)
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .build();
    mRequestMethod = retrofit.create(RequestMethod.class);
    }
    private static class MyBaseHolder{
    private static final MyBaseUtils myBaseUtils = new MyBaseUtils();
    }
    public static MyBaseUtils getInstance(){
    return MyBaseHolder.myBaseUtils;
    }
    //第二步:查询数据嵌套
    private Observable JoinInfo;
    private HashMap<String, Object> hashMap;
    private Observable showInfo;
    public void getShow(final MyCallBack myCallBack){
    HashMap<String, Object> map = new HashMap<>();
    map.put(“phone”,"");//这里需要注册手机号登录
    map.put(“pwd”,"");//密码
    Observable postInfo = mRequestMethod.postInfo(MyUrl.Login, map);
    postInfo.subscribeOn(Schedulers.io())
    .observeOn(Schedulers.io())
    .doOnNext(new Action1() {
    @Override
    public void call(ResponseBody responseBody) {

                        try {
                            Gson gson = new Gson();
                            LoginBean loginBean = gson.fromJson(responseBody.string(), LoginBean.class);
                            if (loginBean.getStatus().equals("0000")){
                                //统一请求头
                                hashMap = new HashMap<>();
                                hashMap.put("userId",loginBean.getResult().getUserId());
                                hashMap.put("sessionId",loginBean.getResult().getSessionId());
    
                                JSONObject object = new JSONObject();
                                object.put("commodityId","29");
                                object.put("count",1);
    
                                JSONObject object1 = new JSONObject();
                                object1.put("commodityId","5");
                                object1.put("count","2");
    
                                JSONObject object2 = new JSONObject();
                                object2.put("commodityId","10");
                                object2.put("count","1");
    						
                                JSONArray array = new JSONArray();
                                array.put(object);
                                array.put(object1);
                                array.put(object2);
                                //同步
                               JoinInfo = mRequestMethod.putInfo(hashMap, MyUrl.JOIN_url, array.toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).flatMap(new Func1<ResponseBody, Observable<ResponseBody>>() {
            @Override
            public Observable<ResponseBody> call(ResponseBody responseBody) {
                return JoinInfo;
            }
        }).doOnNext(new Action1<ResponseBody>() {
            @Override
            public void call(ResponseBody responseBody) {
    
                try {
                    Gson gson = new Gson();
                    JoinBean joinBean = gson.fromJson(responseBody.string(), JoinBean.class);
                    if (joinBean.getStatus().equals("0000")){
                        showInfo = mRequestMethod.showInfo(hashMap, MyUrl.SHOW_url);
                    }
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).flatMap(new Func1<ResponseBody, Observable<ResponseBody>>() {
            @Override
            public Observable<ResponseBody> call(ResponseBody responseBody) {
                return showInfo;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {
    
                    }
    
                    @Override
                    public void onError(Throwable e) {
    
                    }
    
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            myCallBack.onSuccess(responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    
相关标签: 2