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) {
        //更新数据,刷新界面....
        
        }
    }
}

 

posted @ 2015-07-21 15:22  coffeesuke  阅读(3848)  评论(2编辑  收藏  举报