Retrofit+OkHttp+RxJava的使用

依赖

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    //添加ok以及其日志拦截器
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    //logger
    implementation 'com.orhanobut:logger:2.1.1'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation('com.jcodecraeer:xrecyclerview:1.5.9') {
        exclude group: 'com.android.support'
    }

OKHttp

public class OkUtil {
    public static OkHttpClient okHttpClient;

    public static void init() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.readTimeout(3000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(3000, TimeUnit.MILLISECONDS);
        builder.connectTimeout(5000, TimeUnit.MILLISECONDS);
        builder.addInterceptor(new OkHeaderIntorceptor());//添加请求头
        builder.addInterceptor(interceptor  );//添加日志拦截器
        builder.retryOnConnectionFailure(false);
        okHttpClient = builder.build();
    }
}

//请求头

public class OkHeaderIntorceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        builder.addHeader("ak", "0110010010000");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
        String sessionid = SpzUtils.getString(Constant.SESSIONID);
        int userid = SpzUtils.getInt(Constant.USERID,-1);
        builder.addHeader(Constant.SESSIONID, sessionid);
        builder.addHeader(Constant.USERID,userid+"");
        request = builder.build();
        return chain.proceed(request);

    }
}

//log日志

public class OkLogIntorceptor implements Interceptor {
    private static final String TAG = "OkLogInteror";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Log.d(TAG,"请求方法"+request.method());
        Log.d(TAG,"请求网址"+request.url());
        Log.d(TAG,"请求数据"+request.toString());

        //找到请求头
        Headers headers = request.headers();
        //获得set集合
        Set names = headers.names();
        //迭代器
        Iterator iterator = names.iterator();
        //遍历
        while (iterator.hasNext()) {
            //得到值   得到键
            String next = iterator.next();
            //得到值
            String value = headers.get(next);
            LogUtil.d(TAG,next+":"+value);
        }

        return chain.proceed(request);
    }
}

//IBaseCallBack

public interface IBaseCallBack {
    void requestError(ServerException e, int i);
    void retuestSuccess(T t);
    void show();
}

//封装RetrofitUtil类

public class RetrofitUtil {
    private static RetrofitUtil instance;
    private final Retrofit retrofit;

    public static RetrofitUtil getInstance(){
        if(instance==null){
            instance=new RetrofitUtil();
        }
        return instance;
    }

    public RetrofitUtil(){
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlUtil.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(OkHttpUtil.client)
                .build();
    }
    public  T createApi(Class cls){
        T t = retrofit.create(cls);
        return t;
    }
}

//接口

public interface DataService {
    @GET(UrlUtil.BASE_NAB)
    Observable getData(@Query("key") String key, @Query("num") int num);
}

//网络接口UrlUtil

public interface UrlUtil {
    String BASE_URL="http://api.tianapi.com";
    String BASE_NAB="/nba";
}

p层

public class CommentPresent extends IBasePresenter {
    private CommentModel commentModel;

    public CommentPresent(CommentView iBaseView) {
        super(iBaseView);
        commentModel=new CommentModel();
    }

    //评论列表
    public void getComment(int id,int page){
       commentModel.getComment(id, page, new IBaseCallBack() {
           @Override
           public void requestError(ServerException e, int i) {
                    getiBaseView().onDataFailer(e.getMessage());
           }

           @Override
           public void retuestSuccess(CommentBean commentBean) {
               getiBaseView().onDataSuccess(commentBean);
           }

           @Override
           public void show() {

           }
       });
    }
}

model层

public class CommentModel extends BaseModel {

    //评论列表
    public void getComment(int id, int page, final IBaseCallBack callBack){
        CinemaService cinemaService = HttpUtils.getInstance().create(CinemaService.class);
        cinemaService.getComment(InformationUtil.userId(),InformationUtil.sessionId(),id,page,5)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver(callBack){
                    @Override
                    public void onNext(CommentBean commentBean) {
                        super.onNext(commentBean);
                        if (commentBean!=null){
                            if(commentBean.getStatus().equals(Constant.SUCCESS_CODE)){
                                callBack.retuestSuccess(commentBean);
                            }else {
                                loginStatus(commentBean.getMessage());
                            }
                        }else {
                            ToastUtil.showToast(Constant.EMPTY);
                        }
                    }
                });
    }
    }

//basemodel(单点登录)

public class BaseModel {
    public HttpUtils httpUtils;

    public BaseModel() {
        httpUtils = HttpUtils.getInstance();
    }
    public void loginStatus(String msg){
        if (msg.equals(Constant.PLEASE_LOGIN)){
            if (SpzUtils.getBoolean(Constant.ISLOGIN,false)){
                Intent intent = new Intent(App.SContext,LoginActivity.class);
                intent.putExtra(Constant.LOGIN,1);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                App.SContext.startActivity(intent);
                ToastUtil.showToast(Constant.ALREADY_LOGIN);
            }else {
                Intent intent = new Intent(App.SContext,LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                App.SContext.startActivity(intent);
                ToastUtil.showToast(Constant.PLEASE_LOGIN);
            }
        }else {
            ToastUtil.showToast(msg);
        }
    }
}

BaseObser

public class BaseObserver  implements Observer{
    IBaseCallBack callback;

    public BaseObserver(IBaseCallBack callback) {
        this.callback = callback;
    }

    @Override
    public void onSubscribe(Disposable d) {
        boolean isconnected = NetUtils.isconnected(App.SContext);
        if (!isconnected){
            ToastUtil.showToast(Constant.ERROR_NET_WORK);
        }
    }

    @Override
    public void onNext(T t) {
        callback.retuestSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof ConnectException
                || e instanceof TimeoutException
                || e instanceof NetworkErrorException
                || e instanceof UnknownHostException) {
            callback.requestError(ServerException.handleException(e),-1);
        } else {
            callback.requestError(ServerException.handleException(e),-1);
        }

    }

    @Override
    public void onComplete() {

    }
}

fragment

public class CommentFragment extends BaseFragment implements CommentView,CommentAdapter.PraiseClickListener {

    private XRecyclerView xRecyclerView;
    int page=1;
    private CommentAdapter adapter;
    private int id;
    private EditText commentContent;
    private TextView comment;
    private CommentPresent commentPresent;
    private boolean loginStatue;
    private List result;

    @Override
    public void initView() {
        xRecyclerView = view.findViewById(R.id.xRecyclerView);
        commentContent = view.findViewById(R.id.commentContent);
        comment = view.findViewById(R.id.comment);
        id = SpzUtils.getInt(Constant.ID, -1);
        commentPresent = new CommentPresent(this);
        commentPresent.getComment(id,page);
        initLoginStatue();
        showLoadingLayout();
    }
    private void initLoginStatue() {
        loginStatue = GetLoginStatue.getLoginStatue();
    }
    @Subscribe
    public void getLoginStatue(EventLogin eventLogin) {
        initLoginStatue();
        initData();
    }
    @Override
    public void initListener() {
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean loginStatue = GetLoginStatue.getLoginStatue();
                if (!loginStatue){
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                String trim = commentContent.getText().toString().trim();
                commentPresent.getCommentContent(id,trim);
                commentContent.setText("");
            }
        });

//model层应用

public class RetrofitModel {
    public void getData(int num, final RetrofitCallBack retrofitCallBack){
        DataService dataService = RetrofitUtil.getInstance().createApi(DataService.class);
        Subscriber subscriber= (Subscriber) dataService.getData("71e58b5b2f930eaf1f937407acde08fe",num)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Bean picBean) {
                        List newslist = picBean.getNewslist();

                        retrofitCallBack.onSuccess(newslist);


                    }
                });
    }

}

你可能感兴趣的:(Retrofit+OkHttp+RxJava的使用)