Retrofit+okhttp+Rxjava封裝網路請求工具類

ren18234073466發表於2019-01-03

BaseApis

package com.example.renzhili20180103.utils;

import java.util.Map;

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

public interface BeseApis {
    @GET
    Observable<ResponseBody> get(@Url String url);
    @POST
    Observable<ResponseBody> post(@Url String url, @QueryMap Map<String,String> map);
    @Multipart
    @POST
    Observable<ResponseBody> postFormBody(@Url String url, @PartMap Map<String, RequestBody> requestBodyMap);
}

RetrofitUtils

package com.example.renzhili20180103.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
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 RetrofitUtils {
    private static final String BASE_URL ="http://www.zhaoapi.cn/product/" ;
    private static RetrofitUtils mInsaner;
    private final BeseApis beseApis;

    public static RetrofitUtils getmInsaner() {
        if (mInsaner==null){
            synchronized (RetrofitUtils.class){
                mInsaner=new RetrofitUtils();
            }
        }
        return mInsaner;
    }

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

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .client(mClient)
                .build();

        beseApis = retrofit.create(BeseApis.class);
    }
    /**
     * 可以這樣生成Map<String, RequestBody> requestBodyMap
     * Map<String, String> requestDataMap這裡面放置上傳資料的鍵值對。
     */
    public Map<String, RequestBody> generateRequestBody(Map<String, String> requesrDataMap) {
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        for (String key : requesrDataMap.keySet()) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    requesrDataMap.get(key) == null ? "" : requesrDataMap.get(key));
            requestBodyMap.put(key, requestBody);
        }
        return requestBodyMap;
    }
    /**
     * 表單post請求
     */
    public void postFormBody(String url, Map<String, RequestBody> map,HttpListener listener) {
        if (map == null) {
            map = new HashMap<>();
        }
        beseApis.postFormBody(url,map)
                //後臺執行在哪個執行緒
                .subscribeOn(Schedulers.io())
                //最終完成後執行在哪個執行緒
                .observeOn(AndroidSchedulers.mainThread())
                //設定rxjava
                .subscribe(getObserver(listener));

    }

    /**post*/
    public void post(String url, Map<String,String> map,HttpListener listener){
        if (map==null){
            map=new HashMap<>();
        }
        beseApis.post(url,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(listener));

    }
    /**get*/
    public void get(String url,HttpListener listener){

        beseApis.get(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(listener));

    }
    private Observer getObserver(final HttpListener listener) {
        Observer observer = new Observer<ResponseBody>() {
            @Override
            public void onCompleted() {

            }

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

            @Override
            public void onNext(ResponseBody responseBody) {
                try{
                    String data = responseBody.string();
                    if (listener!=null){
                        listener.success(data);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (listener!=null){
                        listener.failed(e.getMessage());
                    }
                }
            }
        };
        return observer;
    }


    public interface HttpListener{
        void success(String data);
        void failed(String error);
    }
}

IView

package com.example.renzhili20180103.view;

public interface IView<T> {
    void onSuccess(T t);
    void onFailed(String error);
}

IPresenter

package com.example.renzhili20180103.presenter;

import com.example.renzhili20180103.model.MyCallBack;

import java.util.Map;

public interface IPresenter {
    void postRequeryData(String url, Map<String,String> params, Class clazz);
    void getRequeryData(String url,Class clazz);
    void postFormBodyRequeryData(String url, Map<String, String> params, Class clazz);
}

IPresenterImpl

package com.example.renzhili20180103.presenter;

import com.example.renzhili20180103.model.IModelImpl;
import com.example.renzhili20180103.model.MyCallBack;
import com.example.renzhili20180103.view.IView;

import java.util.Map;

public class IPresenterImpl implements IPresenter {
    private IView iView;
    private IModelImpl iModel;

    public IPresenterImpl(IView iView) {
        this.iView = iView;
        iModel=new IModelImpl();
    }

    @Override
    public void postRequeryData(String url, Map<String, String> params, Class clazz) {
        iModel.postRequeryData(url, params, clazz, new MyCallBack() {
            @Override
            public void onSuccess(Object o) {
                iView.onSuccess(o);
            }

            @Override
            public void onFailed(String error) {
                iView.onFailed(error);
            }
        });
    }

    @Override
    public void getRequeryData(String url, Class clazz) {
        iModel.getRequeryData(url, clazz, new MyCallBack() {
            @Override
            public void onSuccess(Object o) {
                iView.onSuccess(o);
            }

            @Override
            public void onFailed(String error) {
                iView.onFailed(error);
            }
        });
    }

    @Override
    public void postFormBodyRequeryData(String url, Map<String, String> params, Class clazz) {
        iModel.postFormBodyRequeryData(url, params, clazz, new MyCallBack() {
            @Override
            public void onSuccess(Object o) {
                iView.onSuccess(o);
            }

            @Override
            public void onFailed(String error) {
                iView.onFailed(error);
            }
        });
    }
}

MyCallBack

package com.example.renzhili20180103.model;

public interface MyCallBack <T>{
    void onSuccess(T t);
    void onFailed(String error);
}

IModel

package com.example.renzhili20180103.model;

import java.util.Map;

import okhttp3.RequestBody;

public interface IModel {
    void postRequeryData(String url, Map<String,String> params,Class clazz,MyCallBack myCallBack);
    void getRequeryData(String url,Class clazz,MyCallBack myCallBack);
    void postFormBodyRequeryData(String url, Map<String, String> params, Class clazz, MyCallBack myCallBack);
}

IModelImpl

package com.example.renzhili20180103.model;

import android.support.v7.widget.RecyclerView;

import com.example.renzhili20180103.utils.RetrofitUtils;
import com.google.gson.Gson;

import java.util.Map;

import okhttp3.RequestBody;


public class IModelImpl implements IModel {
    /**
     *post
     *@author Administrator
     *@time 2019/1/3 0003 11:00
     */
    @Override
    public void postRequeryData(String url, Map<String, String> params, final Class clazz, final MyCallBack myCallBack) {
        RetrofitUtils.getmInsaner().post(url, params, new RetrofitUtils.HttpListener() {
            @Override
            public void success(String data) {
                try{
                    Gson gson = new Gson();
                    Object o = gson.fromJson(data, clazz);
                    if (myCallBack!=null){
                        myCallBack.onSuccess(o);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (myCallBack!=null){
                        myCallBack.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void failed(String error) {
                if (myCallBack!=null){
                    myCallBack.onFailed(error);
                }
            }
        });
    }
    /**
     *get
     *@author Administrator
     *@time 2019/1/3 0003 10:54
     */
    @Override
    public void getRequeryData(String url, final Class clazz, final MyCallBack myCallBack) {
        RetrofitUtils.getmInsaner().get(url, new RetrofitUtils.HttpListener() {
            @Override
            public void success(String data) {
                try{
                    Gson gson = new Gson();
                    Object o = gson.fromJson(data, clazz);
                    if (myCallBack!=null){
                        myCallBack.onSuccess(o);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (myCallBack!=null){
                        myCallBack.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void failed(String error) {
                if (myCallBack!=null){
                    myCallBack.onFailed(error);
                }
            }
        });
    }
    /**
     *post表單
     *@author Administrator
     *@time 2019/1/3 0003 10:54
     */
    @Override
    public void postFormBodyRequeryData(String url, Map<String, String> params, final Class clazz, final MyCallBack myCallBack) {
        Map<String, RequestBody> requestBodyMap = RetrofitUtils.getmInsaner().generateRequestBody(params);
        RetrofitUtils.getmInsaner().postFormBody(url, requestBodyMap, new RetrofitUtils.HttpListener() {
            @Override
            public void success(String data) {
                try{
                    Gson gson = new Gson();
                    Object o = gson.fromJson(data, clazz);
                    if (myCallBack!=null){
                        myCallBack.onSuccess(o);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (myCallBack!=null){
                        myCallBack.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void failed(String error) {
                if (myCallBack!=null){
                    myCallBack.onFailed(error);
                }
            }
        });
    }
}

相關文章