美文网首页
Retrofit2+OkHttp3+RxJava网络请求封装

Retrofit2+OkHttp3+RxJava网络请求封装

作者: ShinnyYang_ | 来源:发表于2020-08-18 10:31 被阅读0次

    CSDN :https://blog.csdn.net/shuai497331206

    第一步:  添加依赖

    //RxJava

    implementation 'io.reactivex:rxjava:1.1.3'

    //RxAndroid

    implementation 'io.reactivex:rxandroid:1.1.0'

    //retrofit

    implementation 'com.squareup.retrofit2:retrofit:2.0.0'

    //retrofit依赖Gson

    implementation 'com.squareup.retrofit2:converter-gson:2.0.0'

    //OkHttp

    implementation 'com.squareup.okhttp3:okhttp:3.8.0'

    //retrofit依赖RxJava

    implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

    //okhttp

    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

    //日志

    implementation 'com.orhanobut:logger:2.2.0'

    第二步:

    RetrofitServiceManager

    package com.example.myapplication;

    import com.google.gson.Gson;

    import com.google.gson.GsonBuilder;

    import com.orhanobut.logger.Logger;

    import java.io.IOException;

    import java.util.concurrent.TimeUnit;

    import okhttp3.Interceptor;

    import okhttp3.OkHttpClient;

    import okhttp3.Request;

    import okhttp3.Response;

    import okhttp3.logging.HttpLoggingInterceptor;

    import retrofit2.Retrofit;

    import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

    import retrofit2.converter.gson.GsonConverterFactory;

    /**

    * Created by ShinnyYang on 2020/8/3.

    */

    public class RetrofitServiceManager {

        private static final int DEFAULT_CONNECT_TIME = 12;

        private static final int DEFAULT_WRITE_TIME = 12;

        private static final int DEFAULT_READ_TIME = 12;

        private static OkHttpClient okHttpClient;

        private static final String REQUEST_PATH = "http://admin.qianduoduo.cy6.co";

        private static Retrofit retrofit;

        private RetrofitServiceManager() {

            retrofit = new Retrofit.Builder()

                    .client(initOKHttp())//设置使用okhttp网络请求

                    .baseUrl(REQUEST_PATH)//设置服务器路径

                    .addConverterFactory(GsonConverterFactory.create())//添加转化库,默认是Gson

                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加回调库,采用RxJava

                    .build();

        }

        public static OkHttpClient initOKHttp() {

            if (okHttpClient == null) {

                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(

                        new HttpLoggingInterceptor.Logger() {

                            @Override

                            public void log(String message) {

                                //防止&、=都被转义

                                Logger.e("okhttp==" + message);

                            }

                        }

                );

                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                okHttpClient = new OkHttpClient.Builder()

                        /*  .addInterceptor(new Interceptor() {

                              @Override

                              public Response intercept(Chain chain) throws IOException {

                                  Request request = chain.request()

                                          .newBuilder()

                                          .addHeader("AuthToken", "")

                                          .build();

                                  return chain.proceed(request);

                              }

                          })*/

                        .connectTimeout(12, TimeUnit.SECONDS)

                        .readTimeout(12, TimeUnit.SECONDS)

                        .writeTimeout(12, TimeUnit.SECONDS)

                        .addInterceptor(loggingInterceptor)

                        .build();

            }

            return okHttpClient;

        }

        private static class SingletonHolder {

            private static final RetrofitServiceManager INSTANCE = new RetrofitServiceManager();

        }

        /*

        * 获取RetrofitServiceManager

        **/

        public static RetrofitServiceManager getInstance() {

            return SingletonHolder.INSTANCE;

        }

        public <T> T create(Class<T> service) {

            return retrofit.create(service);

        }

    }

    第三步:

    AllApi

    package com.example.myapplication;

    import com.example.myapplication.bean.HomeListBean;

    import java.util.Map;

    import retrofit2.http.GET;

    import retrofit2.http.Query;

    import retrofit2.http.QueryMap;

    import rx.Observable;

    /**

    * Created by ShinnyYang on 2020/8/3.

    */

    public interface AllApi {

        @GET("/qddapiv2/index/list.php")

        Observable<HomeListBean> getHomeList(@QueryMap Map<String, Object> map);

    }

    第四步:

    HttpModel

    package com.example.myapplication;

    import com.example.myapplication.bean.HomeListBean;

    import java.util.Map;

    import rx.Observable;

    import rx.Observer;

    import rx.android.schedulers.AndroidSchedulers;

    import rx.schedulers.Schedulers;

    /**

    * Created by ShinnyYang on 2020/8/3.

    */

    public class HttpModel {

        private static AllApi movieService = RetrofitServiceManager.getInstance().create(AllApi.class);

        public static void getList(Map<String, Object> map,

                                        Observer<HomeListBean> observer) {

            setSubscribe(movieService.getHomeList(map), observer);

        }

        private static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {

            observable.subscribeOn(Schedulers.io())

                    .subscribeOn(Schedulers.newThread())//子线程访问网络

                    .observeOn(AndroidSchedulers.mainThread())//回调到主线程

                    .subscribe(observer);

        }

    }

    第五步 :

    private void getData() {

        Map<String, Object> map = new HashMap<>();

        map.put("page", "1");

        map.put("auth", "");

        map.put("time", "1596091163");

        map.put("token", "ZcfveU5pHeYiqH6lfvE9qeIquMPVGnSloW7TYnryFCI=");

        map.put("uid", "0730096");

        map.put("action", "margin");

        map.put("device_no", "ece430f2-cda1-4c5c-be1e-a0657395470e");

        HttpModel.getList(map, new Observer<HomeListBean>() {

                    @Override

                    public void onCompleted() {

                        Toast.makeText(getApplicationContext(), "onCompleted", Toast.LENGTH_SHORT).show();

                    }

                    @Override

                    public void onError(Throwable e) {

                        Logger.e("onError==>" + e.getMessage());

                    }

                    @Override

                    public void onNext(HomeListBean homeListBean) {

                        Logger.e("onSuccess==>" + homeListBean.toString());

                    }

                });

    }

    实体Bean

    package com.example.myapplication.bean;

    import java.util.List;

    public class HomeListBean {

    /**

    * status : 1

    * time : 1595819291

    * pagenum : 1

    * data : [{"task_id":"254","type_id":"11","thumb":"http://admin.qianduoduo.cy6.co/api/img/5.png","title":"999999999999999","unit_price":"400.00","num":"12","is_jingpin":"0","margin_per":1,"finish":2,"type_name":"微信转发","extra":"75"}]

    * msg : 查询成功

    */

        private int status;

        private int time;

        private int pagenum;

        private Stringmsg;

        private Listdata;

        public int getStatus() {

    return status;

        }

    public void setStatus(int status) {

    this.status = status;

        }

    public int getTime() {

    return time;

        }

    public void setTime(int time) {

    this.time = time;

        }

    public int getPagenum() {

    return pagenum;

        }

    public void setPagenum(int pagenum) {

    this.pagenum = pagenum;

        }

    public StringgetMsg() {

    return msg;

        }

    public void setMsg(String msg) {

    this.msg = msg;

        }

    public ListgetData() {

    return data;

        }

    public void setData(List data) {

    this.data = data;

        }

    @Override

        public StringtoString() {

    return "HomeListBean{" +

    "status=" +status +

    ", time=" +time +

    ", pagenum=" +pagenum +

    ", msg='" +msg +'\'' +

    ", data=" +data +

    '}';

        }

    public static class DataBean {

    /**

    * task_id : 254

    * type_id : 11

    * thumb : http://admin.qianduoduo.cy6.co/api/img/5.png

    * title : 999999999999999

    * unit_price : 400.00

    * num : 12

    * is_jingpin : 0

    * margin_per : 1

    * finish : 2

    * type_name : 微信转发

    * extra : 75

    */

            private Stringtask_id;

            private Stringtype_id;

            private Stringthumb;

            private Stringtitle;

            private Stringunit_price;

            private Stringnum;

            private Stringis_jingpin;

            private int margin_per;

            private int finish;

            private Stringtype_name;

            private Stringextra;

            @Override

            public StringtoString() {

    return "DataBean{" +

    "task_id='" +task_id +'\'' +

    ", type_id='" +type_id +'\'' +

    ", thumb='" +thumb +'\'' +

    ", title='" +title +'\'' +

    ", unit_price='" +unit_price +'\'' +

    ", num='" +num +'\'' +

    ", is_jingpin='" +is_jingpin +'\'' +

    ", margin_per=" +margin_per +

    ", finish=" +finish +

    ", type_name='" +type_name +'\'' +

    ", extra='" +extra +'\'' +

    '}';

            }

    public StringgetTask_id() {

    return task_id;

            }

    public void setTask_id(String task_id) {

    this.task_id = task_id;

            }

    public StringgetType_id() {

    return type_id;

            }

    public void setType_id(String type_id) {

    this.type_id = type_id;

            }

    public StringgetThumb() {

    return thumb;

            }

    public void setThumb(String thumb) {

    this.thumb = thumb;

            }

    public StringgetTitle() {

    return title;

            }

    public void setTitle(String title) {

    this.title = title;

            }

    public StringgetUnit_price() {

    return unit_price;

            }

    public void setUnit_price(String unit_price) {

    this.unit_price = unit_price;

            }

    public StringgetNum() {

    return num;

            }

    public void setNum(String num) {

    this.num = num;

            }

    public StringgetIs_jingpin() {

    return is_jingpin;

            }

    public void setIs_jingpin(String is_jingpin) {

    this.is_jingpin = is_jingpin;

            }

    public int getMargin_per() {

    return margin_per;

            }

    public void setMargin_per(int margin_per) {

    this.margin_per = margin_per;

            }

    public int getFinish() {

    return finish;

            }

    public void setFinish(int finish) {

    this.finish = finish;

            }

    public StringgetType_name() {

    return type_name;

            }

    public void setType_name(String type_name) {

    this.type_name = type_name;

            }

    public StringgetExtra() {

    return extra;

            }

    public void setExtra(String extra) {

    this.extra = extra;

            }

    }

    }

      完成!!!!!

    常用的注解:

    @GET GET请求方式

    @POST POST请求方式

    @Query GET请求参数

    @Header用来添加Header请求头

    @FormUrlEncoded post请求头标示 其他注解请求方式:

    @PUT 表示这是一个PUT请求

    @DELETE 表示这是一个DELETE请求

    @HEAD 表示这是一个HEAD请求

    @OPTIONS 表示这是一个OPTION请求

    @PATCH 表示这是一个PAT请求

    相关文章

      网友评论

          本文标题:Retrofit2+OkHttp3+RxJava网络请求封装

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