1. 程式人生 > >基於OkHttp 3封裝的網路請求

基於OkHttp 3封裝的網路請求

首先匯入okhttp

compile 'com.squareup.okhttp3:okhttp:3.7.0'

封裝的主要類

OkHttpHelper主要是封裝的OkHttpClient以及請求引數的封裝
BaseCallback 輔助類
SpotsCallBack載入的提示框,可以更改

OkHttpHelper類

首先把它做成一個單例

   private static class singleHolder {
        private static final OkHttpHelper instance = new OkHttpHelper();
    }

    private OkHttpHelper() {
        okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(10, TimeUnit.SECONDS)//設定讀取超時時間
                .writeTimeout(10, TimeUnit.SECONDS)//設定寫的超時時間
                .connectTimeout(10, TimeUnit.SECONDS)//設定連線超時時間
                .build();
        mGson = new Gson();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static OkHttpHelper getInstance() {

        return singleHolder.instance;
    }

在封裝BaseCallback因為我們要根據它得到型別

static Type getSuperclassTypeParameter(Class<?> subclass) {

        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterizedType = (ParameterizedType) superclass;

        return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
    }

然後在封裝doRequest方法

   private void doRequest(Request request, final BaseCallback callback) {
        callback.onRequestBefore(request);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(call.request(), e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.OnResponse(response);
                if (response.isSuccessful()) {
                    if (callback.mType == String.class) {
                        String resultStr = response.body().string();

                        LogHelper.i("String 請求到的資料:" + resultStr);
                        callbackSuccess(callback, response, resultStr);
                    } else if (("" + callback.mType).equals("byte[]")) {
                        byte[] resultStr = response.body().bytes();
                        LogHelper.i("byte 請求到的資料:" + resultStr);
                        callbackSuccess(callback, response, resultStr);
                    } else {
                        try {
                            String resultStr = response.body().string();
                            LogHelper.i("json 請求到的資料:" + resultStr);
                            Object object = mGson.fromJson(resultStr, callback.mType);
                            callbackSuccess(callback, response, object);
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackError(callback, response, response.code(), e);
                        }
                    }

                } else {
                    callback.onError(response, response.code(), null);
                }
            }
        });
    }

最後測試

//請求引數
   Map<String, String> map = new HashMap<>();
        
        OkHttpHelper.getInstance().post("請求的地址", map, new SpotsCallBack<BannerClazz>(UIUtils.getContext(), false) {
            @Override
            public void onSuccess(Response response, BannerClazz bannerClazz) {
                    iBannerInterface.bannerSuccess(bannerClazz);
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });

下邊貼出完整程式碼

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OkHttpHelper {
    private static OkHttpClient okHttpClient;
    private Gson mGson;
    private Handler mHandler;

    private static class singleHolder {
        private static final OkHttpHelper instance = new OkHttpHelper();
    }

    private OkHttpHelper() {
        okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(10, TimeUnit.SECONDS)//設定讀取超時時間
                .writeTimeout(10, TimeUnit.SECONDS)//設定寫的超時時間
                .connectTimeout(10, TimeUnit.SECONDS)//設定連線超時時間
                .build();
        mGson = new Gson();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static OkHttpHelper getInstance() {

//        return new OkHttpHelper();
        return singleHolder.instance;
    }

    private void doRequest(Request request, final BaseCallback callback) {
        callback.onRequestBefore(request);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(call.request(), e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.OnResponse(response);
                if (response.isSuccessful()) {
                    if (callback.mType == String.class) {
                        String resultStr = response.body().string();

                        LogHelper.i("String 請求到的資料:" + resultStr);
                        callbackSuccess(callback, response, resultStr);
                    } else if (("" + callback.mType).equals("byte[]")) {
                        byte[] resultStr = response.body().bytes();
                        LogHelper.i("byte 請求到的資料:" + resultStr);
                        callbackSuccess(callback, response, resultStr);
                    } else {
                        try {
                            String resultStr = response.body().string();
                            LogHelper.i("json 請求到的資料:" + resultStr);
                            Object object = mGson.fromJson(resultStr, callback.mType);
                            callbackSuccess(callback, response, object);
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackError(callback, response, response.code(), e);
                        }
                    }

                } else {
                    callback.onError(response, response.code(), null);
                }
            }
        });
    }


    public void get(String url, BaseCallback callback) {
        Request request = buildRequest(url, null, HttpMethodType.GET);

        doRequest(request, callback);
    }

    public void post(String url, Map<String, String> params, BaseCallback callback) {
        Request request = buildRequest(url, params, HttpMethodType.POST);
        doRequest(request, callback);
    }

    public void file(String url, String localPath, BaseCallback callback) {
        if (!CommonUtil.getInstance().judgeStrIsNull(url) &&
                !CommonUtil.getInstance().judgeStrIsNull(localPath)) {
            File file = new File(localPath);
            if (!file.exists()) {
                LogHelper.e("該路徑下找不到此檔案");
                return;
            }

            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            // 初始化請求體物件,設定Content-Type以及檔案資料流
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM) // multipart/form-data
                    .addFormDataPart("file", file.getName(), body)
                    .build();

            Request request = new Request.Builder().url(url).post(requestBody).build();
            doRequest(request, callback);

        } else {
            LogHelper.e("本地路徑或者伺服器上傳路徑為空");
        }
    }


    private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        LogHelper.i("Request Url::" + url);
        if (methodType == HttpMethodType.GET) {
            builder.get();
        } else if (methodType == HttpMethodType.POST) {
            RequestBody body = buildFormData(params);
            builder.post(body);
        }

        return builder.build();
    }

    private RequestBody buildFormData(Map<String, String> params) {
        FormBody.Builder body = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    LogHelper.i("key::" + entry.getKey() + "--value::" + entry.getValue());
                    if (!CommonUtil.getInstance().judgeStrIsNull(entry.getKey())) {
                        body.add(entry.getKey(), entry.getValue());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }
        return body.build();
    }

    enum HttpMethodType {
        GET, POST
    }

    private void callbackSuccess(final BaseCallback callback, final Response response, final Object object) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onSuccess(response, object);
            }
        });

    }

    private void callbackError(final BaseCallback callback, final Response response, final int code, final Exception e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onError(response, code, e);
            }
        });

    }
}
public abstract class BaseCallback<T> {
    Type mType;
    public BaseCallback() {
        mType = getSuperclassTypeParameter(getClass());
    }



    static Type getSuperclassTypeParameter(Class<?> subclass) {

        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterizedType = (ParameterizedType) superclass;

        return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
    }

    public abstract void onRequestBefore(Request request);

    public abstract void onFailure(Request request, IOException e);

    public abstract void onSuccess(Response response, T t);

    public abstract void onError(Response response, int code, Exception e);

    public abstract void OnResponse(Response response);
}
public abstract class SpotsCallBack<T> extends BaseCallback<T> {
    private SpotsDialog dialog;
    private boolean isShow = true;

    public SpotsCallBack(Context context) {
        try {
            dialog = new SpotsDialog(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
        setMessage("載入中......");
    }

    public SpotsCallBack(Context context, boolean show) {
        this.isShow = show;
        if(isShow){
            try {
                dialog = new SpotsDialog(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        setMessage("載入中......");
    }

    public SpotsCallBack(Context context, String message) {
        try {
            dialog = new SpotsDialog(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(message)) {
            setMessage(message);
        }

    }

    protected void showDialog() {
        try {
            if (dialog != null) {
                dialog.show();
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }

    }

    protected void dismissDialog() {
        try {
            if (dialog != null)
                dialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void setMessage(String message) {

        try {
            if (dialog != null) {
                dialog.setMessage(message);
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }

    @Override
    public void onRequestBefore(Request request) {
        if (isShow)
            showDialog();
    }



    @Override
    public void onFailure(Request request, IOException e) {
        dismissDialog();
    }

    @Override
    public void OnResponse(Response response) {
        dismissDialog();
    }
}