1. 程式人生 > >OkHttp網路連線封裝工具類以及json轉換類

OkHttp網路連線封裝工具類以及json轉換類

public class OkHttpUtils {  
  
    private static final String TAG = "OkHttpUtils";  
  
    private static OkHttpUtils mInstance;  
    private OkHttpClient mOkHttpClient;  
    private Handler mHandler;  
  
    private OkHttpUtils() {  
        /** 
         * 構建OkHttpClient 
         */  
        mOkHttpClient = new OkHttpClient();  
        /** 
         * 設定連線的超時時間 
         */  
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);  
        /** 
         * 設定響應的超時時間 
         */  
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);  
        /** 
         * 請求的超時時間 
         */  
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);  
        /** 
         * 允許使用Cookie 
         */  
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));  
        /** 
         * 獲取主執行緒的handler 
         */  
        mHandler = new Handler(Looper.getMainLooper());  
    }  
  
    /** 
     * 通過單例模式構造物件 
     * @return OkHttpUtils 
     */  
    private synchronized static OkHttpUtils getmInstance() {  
        if (mInstance == null) {  
            mInstance = new OkHttpUtils();  
        }  
        return mInstance;  
    }  
  
    /** 
     * 構造Get請求 
     * @param url  請求的url 
     * @param callback  結果回撥的方法 
     */  
    private void getRequest(String url, final ResultCallback callback) {  
        final Request request = new Request.Builder().url(url).build();  
        deliveryResult(callback, request);  
    }  
  
    /** 
     * 構造post 請求 
     * @param url 請求的url 
     * @param callback 結果回撥的方法 
     * @param params 請求引數 
     */  
    private void postRequest(String url, final ResultCallback callback, List<Param> params) {  
        Request request = buildPostRequest(url, params);  
        deliveryResult(callback, request);  
    }  
  
    /** 
     * 處理請求結果的回撥 
     * @param callback 
     * @param request 
     */  
    private void deliveryResult(final ResultCallback callback, Request request) {  
  
        mOkHttpClient.newCall(request).enqueue(new Callback() {  
            @Override  
            public void onFailure(Request request, final IOException e) {  
                sendFailCallback(callback, e);  
            }  
  
            @Override  
            public void onResponse(Response response) throws IOException {  
                try {  
                    String str = response.body().string();  
                    if (callback.mType == String.class) {  
                        sendSuccessCallBack(callback, str);  
                    } else {  
                        Object object = JsonUtils.deserialize(str, callback.mType);  
                        sendSuccessCallBack(callback, object);  
                    }  
                } catch (final Exception e) {  
                    LogUtils.e(TAG, "convert json failure", e);  
                    sendFailCallback(callback, e);  
                }  
  
            }  
        });  
    }  
  
    /** 
     * 傳送失敗的回撥 
     * @param callback 
     * @param e 
     */  
    private void sendFailCallback(final ResultCallback callback, final Exception e) {  
        mHandler.post(new Runnable() {  
            @Override  
            public void run() {  
                if (callback != null) {  
                    callback.onFailure(e);  
                }  
            }  
        });  
    }  
  
    /** 
     * 傳送成功的調 
     * @param callback 
     * @param obj 
     */  
    private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {  
        mHandler.post(new Runnable() {  
            @Override  
            public void run() {  
                if (callback != null) {  
                    callback.onSuccess(obj);  
                }  
            }  
        });  
    }  
  
    /** 
     * 構造post請求 
     * @param url  請求url 
     * @param params 請求的引數 
     * @return 返回 Request 
     */  
    private Request buildPostRequest(String url, List<Param> params) {  
        FormEncodingBuilder builder = new FormEncodingBuilder();  
        for (Param param : params) {  
            builder.add(param.key, param.value);  
        }  
        RequestBody requestBody = builder.build();  
        return new Request.Builder().url(url).post(requestBody).build();  
    }  
  
  
    /**********************對外介面************************/  
  
    /** 
     * get請求 
     * @param url  請求url 
     * @param callback  請求回撥 
     */  
    public static void get(String url, ResultCallback callback) {  
        getmInstance().getRequest(url, callback);  
    }  
  
    /** 
     * post請求 
     * @param url       請求url 
     * @param callback  請求回撥 
     * @param params    請求引數 
     */  
    public static void post(String url, final ResultCallback callback, List<Param> params) {  
        getmInstance().postRequest(url, callback, params);  
    }  
  
    /** 
     * http請求回撥類,回撥方法在UI執行緒中執行 
     * @param <T> 
     */  
    public static abstract class ResultCallback<T> {  
  
        Type mType;  
  
        public ResultCallback(){  
            mType = getSuperclassTypeParameter(getClass());  
        }  
  
        static Type getSuperclassTypeParameter(Class<?> subclass) {  
            Type superclass = subclass.getGenericSuperclass();//返回父類的型別  
            if (superclass instanceof Class) {  
                throw new RuntimeException("Missing type parameter.");  
            }  
            ParameterizedType parameterized = (ParameterizedType) superclass;  
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);  
        }  
  
        /** 
         * 請求成功回撥 
         * @param response 
         */  
        public abstract void onSuccess(T response);  
  
        /** 
         * 請求失敗回撥 
         * @param e 
         */  
        public abstract void onFailure(Exception e);  
    }  
  
    /** 
     * post請求引數類 
     */  
    public static class Param {  
  
        String key;//請求的引數  
        String value;//引數的值  
  
        public Param() {  
        }  
  
        public Param(String key, String value) {  
            this.key = key;  
            this.value = value;  
        }  
  
    }  
  
  
}  
Json轉換工具類
public class JsonUtils {

    private static Gson mGson = new Gson();

    /**
     * 將物件準換為json字串
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String serialize(T object) {
        return mGson.toJson(object);
    }

    /**
     * 將json字串轉換為物件
     * @param json
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
        return mGson.fromJson(json, clz);
    }

    /**
     * 將json物件轉換為實體物件
     * @param json
     * @param clz
     * @param <T>
     * @return
     * @throws JsonSyntaxException
     */
    public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
        return mGson.fromJson(json, clz);
    }

    /**
     * 將json字串轉換為物件
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
        return mGson.fromJson(json, type);
    }






}


使用:
 OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                List<NewsBean> newsBeanList = NewsJsonUtils.readJsonNewsBeans(response, getID(type));
                listener.onSuccess(response
); } @Override public void onFailure(Exception e) { listener.onFailure("load news list failure.", e); } }; OkHttpUtils.get(url, loadNewsCallback);