Android網路架構之———OkHttp+Volley+Gson,okhttpgson

來源:互聯網
上載者:User

Android網路架構之———OkHttp+Volley+Gson,okhttpgson

之前都是用自己封裝的HttpClient,不過現在主流的網路請求都是用Volley,OkHttp呼聲也很高。

這幾個架構就不做介紹了,本文為Volley結合OkHttp處理Http請求,再結合Gson自訂Request實現Android網路功能

準備jar包:

,忽略universal-image-loader,懶得刪了

 

RequestQueue只需要一個就好,所以我們把它放到StaticVariable中

import com.android.volley.RequestQueue;import com.liujing.csoc.utils.HttpUtils;public class StaticVariable {    private static RequestQueue mRequestQueue;    public static void clear() {        HttpUtils.cancelAllRequest();        mRequestQueue = null;    }    public static RequestQueue getRequestQueue() {        return mRequestQueue;    }    public static void setRequestQueue(RequestQueue paramRequestQueue) {        mRequestQueue = paramRequestQueue;    }}
import java.io.IOException;import java.net.HttpURLConnection;import java.net.URL;import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.HurlStack;import com.android.volley.toolbox.Volley;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.OkUrlFactory;import com.liujing.csoc.application.TopSecCsocApplication;import com.liujing.csoc.iconstant.StaticVariable;public class HttpUtils {    /**     * 添加Request請求到隊列中,因為我們使用OkHttp作為Volley的傳輸層,所以增加一個HttpStack參數     * @param request     */    public static void addRequest(Request<?> request) {        if (request != null) {            if (StaticVariable.getRequestQueue() == null) {                StaticVariable.setRequestQueue(Volley                        .newRequestQueue(TopSecCsocApplication.getContext()));            }            Volley.newRequestQueue(TopSecCsocApplication.getContext(), new OkHttpStack());            StaticVariable.getRequestQueue().add(request);        }    }    /**     * 取消所有Request     */    public static void cancelAllRequest() {        RequestQueue localRequestQueue = StaticVariable.getRequestQueue();        if (localRequestQueue != null) {            localRequestQueue.cancelAll(new RequestQueue.RequestFilter() {                @Override                public boolean apply(Request<?> request) {                    return true;                }            });            localRequestQueue.stop();        }    }    /**     * 根據標籤取消指定Request     * @param tag     */    public static void cancelRequestByTag(String tag) {        if (!TextUtils.isEmpty(tag)) {            if (StaticVariable.getRequestQueue() != null) {                StaticVariable.getRequestQueue().cancelAll(tag);            }        }    }        /**     * 定義OkHttpStack     * @author Administrator     *     */    private static class OkHttpStack extends HurlStack {        private final OkUrlFactory okUrlFactory;        public OkHttpStack() {            this(new OkUrlFactory(new OkHttpClient()));        }        public OkHttpStack(OkUrlFactory okUrlFactory) {            if (okUrlFactory == null) {                throw new NullPointerException("Client must not be null.");            }            this.okUrlFactory = okUrlFactory;        }        @Override        protected HttpURLConnection createConnection(URL url)                throws IOException {            return okUrlFactory.open(url);        }    }}

 

結合Gson自訂Request

import java.io.UnsupportedEncodingException;import java.lang.reflect.Type;import java.util.Iterator;import java.util.Map;import com.android.volley.AuthFailureError;import com.android.volley.NetworkResponse;import com.android.volley.ParseError;import com.android.volley.Request;import com.android.volley.Response;import com.android.volley.Response.ErrorListener;import com.android.volley.Response.Listener;import com.android.volley.toolbox.HttpHeaderParser;import com.google.gson.Gson;/** * Volley自訂Request * @author liujing * @param <T> */public class CsocRequest<T> extends Request<T> {    public static final int GET = Method.GET;    public static final int POST = Method.POST;    private static Gson gson = new Gson();    private Type mType;    private final ResponeListener<T> mlistener;    private Map<String, String> mParams;        //自訂回調,方便使用    public interface ResponeListener<T> extends ErrorListener, Listener<T> {    }    /**     * 預設get方式提交http請求     * @param url     * @param type     * @param params     * @param listener     */    public CsocRequest(String url, Type type, Map<String, String> params,            ResponeListener<T> listener) {        super(GET, getUrl(url, params), listener);        this.mlistener = listener;        this.mType = type;        setShouldCache(false);    }    /**     * 增加method參數選擇get或post方式提交http請求     * @param method     * @param url     * @param type     * @param params     * @param listener     */    public CsocRequest(int method, String url, Type type,            Map<String, String> params, ResponeListener<T> listener) {        super(method,method==POST?url:getUrl(url, params), listener);        this.mlistener = listener;        this.mType = type;        if(method==POST){            mParams = params;        }        setShouldCache(false);    }        @Override    protected Map<String, String> getParams() throws AuthFailureError {        if (mParams != null) {            return mParams;        } else {            return super.getParams();        }    }    //構造url,get方式請求也可直接傳參數    private static String getUrl(String url, Map<String, String> params) {        if (params != null) {            Iterator<String> it = params.keySet().iterator();            StringBuffer sb = null;            while (it.hasNext()) {                String key = it.next();                String value = params.get(key);                if (sb == null) {                    sb = new StringBuffer();                    sb.append("?");                } else {                    sb.append("&");                }                sb.append(key);                sb.append("=");                sb.append(value);            }            url += sb.toString();        }        return url;    }    @Override    protected Response<T> parseNetworkResponse(NetworkResponse response) {        try {            T result;            String jsonStr = new String(response.data,                    HttpHeaderParser.parseCharset(response.headers));            result = gson.fromJson(jsonStr, mType);            return Response.success(result,                    HttpHeaderParser.parseCacheHeaders(response));        } catch (UnsupportedEncodingException e) {            e.printStackTrace();            return Response.error(new ParseError(e));        }    }    @Override    protected void deliverResponse(T response) {        mlistener.onResponse(response);    }}

 

大功告成,看看怎麼用吧,其實就是new一個Request,再通過HttpUtils添加到隊列中

Params get或post的請求參數

url   就是url

type  Gson根據Type解析json

private void loadData(int pageNUM, String loadDate) {        Map<String, String> Params = new HashMap<String, String>();        Params.put("cusId", customerId);        Params.put("session_id", mSession_id);        Params.put("pageNo", String.valueOf(pageNUM));        Params.put("pageSize", String.valueOf(IConstant.PAGE_LOAD_NUM));        Params.put("date", loadDate);        String url = IConfig.URL + IConfig.CONTENT_MONITOR;        Type type = new TypeToken<ResultData<ContentMonitorBean<ContentMonitorDataBean>>>() {
     }.getType(); CsocRequest<ResultData<BaseBean>> cr = new CsocRequest<ResultData<BaseBean>>( url, type, Params, this); HttpUtils.addRequest(cr); }

 

接收請求結果,重新整理介面

實現前面定義的ResponeListener,onErrorResponse和onResponse代表請求失敗和成功

public class BaseFragment extends Fragment implements ResponeListener<ResultData<BaseBean>> {    @Override    public void onErrorResponse(VolleyError error) {        dismissNetDialog();        Toast.makeText(mActivity, "載入失敗", Toast.LENGTH_SHORT).show();    };        @Override    public void onResponse(ResultData<BaseBean> response) {        dismissNetDialog();        if (response != null) {        //更新資料,重新整理介面....                }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.