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

封装网络请求

程序员文章站 2022-06-05 21:09:23
...

V层

package com.cn.kj.view;
public interface IView<T> {
    void setsuccessed(T data);
}

P层

package com.cn.kj.presenter;

import java.util.Map;

public interface IP {
    void setGetRequest(String url,Class clazz);
    void setPostRequest(String url, Map<String,String> map,Class clazz);
}


package com.cn.kj.presenter;

import com.cn.kj.model.IModel;
import com.cn.kj.mycallback.MyCallBack;
import com.cn.kj.view.IView;

import java.util.Map;

public class IPresenter implements IP{

    IView mIView;
    IModel mIModel;

    public IPresenter(IView IView) {
        mIView = IView;
        mIModel=new IModel();
    }

    @Override
    public void setGetRequest(String url, Class clazz) {
        mIModel.setGetResponse(url, clazz, new MyCallBack() {
            @Override
            public void setData(Object data) {
                mIView.setsuccessed(data);
            }
        });
    }

    @Override
    public void setPostRequest(String url, Map<String, String> map, Class clazz) {
        mIModel.setPostResponse(url, map, clazz, new MyCallBack() {
            @Override
            public void setData(Object data) {
                mIView.setsuccessed(data);
            }
        });
    }

    public void onDistouch(){
        if(mIModel!=null){
            mIModel=null;
        }
        if(mIView!=null){
            mIView=null;
        }
    }
}

M层

package com.cn.kj.model;

import com.cn.kj.mycallback.MyCallBack;

import java.util.Map;

public interface IM {
    void setGetResponse(String url, Class clazz, MyCallBack myCallBack);
    void setPostResponse(String url, Map<String,String> map, Class clazz,MyCallBack myCallBack);
}


package com.cn.kj.model;

import android.util.Log;

import com.cn.kj.mycallback.MyCallBack;
import com.cn.kj.utils.RetrofitManager;
import com.google.gson.Gson;

import java.util.Map;

public class IModel implements IM{
    @Override
    public void setGetResponse(String url, final Class clazz, final MyCallBack myCallBack) {
        RetrofitManager.getInstance().get(url).result(new RetrofitManager.HttpListener() {
            @Override
            public void onSuccessed(String data) {
                Object o = new Gson().fromJson(data, clazz);
                myCallBack.setData(o);
            }

            @Override
            public void onFail(String data) {
                Log.e("sjx",data);
            }
        });
    }

    @Override
    public void setPostResponse(String url, Map<String, String> map, final Class clazz, final MyCallBack myCallBack) {
        RetrofitManager.getInstance().post(url,map).result(new RetrofitManager.HttpListener() {
            @Override
            public void onSuccessed(String data) {
                Object o = new Gson().fromJson(data, clazz);
                myCallBack.setData(o);
            }

            @Override
            public void onFail(String data) {

            }
        });
    }
}

M层与P层的回调接口

package com.cn.kj.mycallback;

public interface MyCallBack<T>{
    void setData(T data);
}

封装retrofit,Rxjava,Okhttp

package com.cn.kj.utils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class RetrofitManager<T> {
    private static RetrofitManager mRetrofitManager;
    private final BaseApis mBaseApis;

    public static synchronized RetrofitManager getInstance(){
        if(mRetrofitManager==null){
            mRetrofitManager=new RetrofitManager();
        }
        return mRetrofitManager;
    }
    private RetrofitManager(){

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.writeTimeout(10,TimeUnit.SECONDS);
        builder.readTimeout(10,TimeUnit.SECONDS);
        builder.connectTimeout(10,TimeUnit.SECONDS);
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        builder.retryOnConnectionFailure(true);
        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Constant.Base_Url)
                .client(client)
                .build();
        mBaseApis = retrofit.create(BaseApis.class);
    }

    public RetrofitManager get(String url){
        mBaseApis.get(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return mRetrofitManager;
    }

    public RetrofitManager post(String url, Map<String,String> map){
        if (map==null){
            map=new HashMap<>();
        }
        mBaseApis.post(url,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return mRetrofitManager;
    }

    private Observer observer=new Observer<ResponseBody>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            if(listener!=null){
                listener.onFail(e.getMessage());
            }
        }

        @Override
        public void onNext(ResponseBody responseBody) {
            try {
                String data = responseBody.string();
                if(listener!=null){
                    listener.onSuccessed(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
                if(listener!=null){
                    listener.onSuccessed(e.getMessage());
                }
            }
        }

    };

    public interface HttpListener{
        void onSuccessed(String data);
        void onFail(String data);
    }

    private HttpListener listener;

    public void result(HttpListener listener){
        this.listener=listener;
    }
}

请求方法

package com.cn.kj.utils;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import rx.Observable;

public interface BaseApis {

    @GET
    Observable<ResponseBody> get(@Url String url);

    @POST
    Observable<ResponseBody> post(@Url String url, @QueryMap Map<String,String> map);

}