你的位置:首页 > 操作系统

[操作系统]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) {    //更新数据,刷新界面....        }  }}

 




深圳去贵州旅游报价跟团去贵州旅游多少钱几月去贵州旅游最好去贵州的旅游团价格去贵州旅游必去景点南海影视城4月好玩活动?佛山南海影视城怎么样? 神龙水世界景区门票包含什么?桂林神龙水世界有什么另收费项目? 桂林到神龙水世界自驾游攻略?桂林到神龙水世界景区开车攻略? 南海影视城最新活动时间?佛山南海影视城4月有什么优惠? 济南春季赏花指南 寻找醉美“花花世界” 香市动物园有什么动物表演?东莞香市动物园动物表演一天有几场? 香市动物园有动物表演吗?东莞香市动物园动物表演时间表? 3月松山湖桃花开了吗?2015松山湖桃花几月最好看? 张家界和凤凰如何花最少的钱? 周末溱湖游 秋风吹过芦苇塘 深圳观澜版画村在哪里、怎么去? 云南大海草山怎么去? 去泰国旅游的最佳时期是什么时候?天气怎么样? 迪拜帆船酒店住一晚多少钱? 曼谷玉佛寺怎么去?曼谷玉佛寺怎么坐车? 2015年七夕去马尔代夫玩好不好? IDT5V9888NLGI8 Datasheet IDT5V9888NLGI8 Datasheet IDT71V3558XS133PFGI Datasheet IDT71V3558XS133PFGI Datasheet IDT72V3650L10PF8 Datasheet IDT72V3650L10PF8 Datasheet 武汉香港旅游价格 武汉香港旅游价格 武汉香港旅游价格 苏州到香港旅游价格 苏州到香港旅游价格 苏州到香港旅游价格 南京到香港旅游价格 南京到香港旅游价格 南京到香港旅游价格