Android網絡架構之———OkHttp+Volley+Gson


之前都是用自己封裝的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) {
        //更新數據,刷新界面....
        
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM