13.网络框架的实现

基本架构为四个部分:Request、RequestQueue、NetworkExecutors(Threads)、Response Delivery
首先定义网络请求方式:

public static enum HttpMethod {
  GET("GET"),POST("POST"),PUT("PUT"),DELETE("DELETE");

  private String mHttpMethod="";

  private HttpMethod(String method) {
    mHttpMethod = method;
  }

  @Override
  public String toString() {
    return mHttpMethod;
  }
}

public static enum Priority {
  LOW,NORMAL,HIGN,IMMEDIATE
}

Request类核心代码:

public abstract class Requset implements Comparable> {
  private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
  protected int mSerialNum = 0;
  protected Priority mPriority = Priority.NORMAL;
  protected boolean isCancel = false;
  private boolean mShouldCache = true;
  protected RequestListener mRequestListener;
  private String mUrl = "";
  HttpMethod mHttpMethod = HttpMethod.GET;
  private Map mHeaders = new HashMap();
  private Map mBodyParams = new HashMap();

  public Request(HttpMethod method,String url,RequestListener listener) {
    mHttpMethod = method;
    mUrl = url;
    mRequestListener = listener;
  }
  
  public abstract T parseResponse(Response response);
  public final void deliveryResponse(Response response) {
    T result = parseResponse(response);
    if (mRequestListener != null ) {
      int stCode = response != null ? response.getStatusCode(): - 1;
      String msg = response != null ? response.getMessage():"unknow error";
      mRequestListener.onComplete(stCode,result,msg);
}
}

protected String getParamsEncoding() {
  return DEFAULT_PARAMS_ENCODING;
 }

  public String getBodyContentType() {
    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
  }

  public byte[] getBody() {
    Map params = getParams();
    if (params != null && Params.size() > 0) {
      return encodeParameters(params,getParamsEncoding());
    }
    return null;
  }

  private byte[] encodeParameters(Map params,String paramsEncoding) {
    StringBuilder encodeParams = new StringBuilder();
    try {
      for (Map.Entry entry:params.entrySet()) {
        encodedParams.append(URLEncoder.encode(entry.getKey(),paramsEncoding));
      encodedParams.append('=');
      encodedParams.append(URLEncoder.encode(entry.getValue(),paramsEncoding));
    encodedParams.append('&');
      }
      return encodeParams.toString().getBytes(paramsEncoding);
    } catch (UnsupportedEncodingException uee) {
      throw new RuntimeException("Encoding not supported:" + paramsEncoding,uee);
    }
  }

@Override
  public int compareTo(Request another) {
    Priority myPriority = this.getPriority();
    Priority anotherPriority = another.getPriority();
    return myPriority.equals(another)?this.getSerialNumber() - another.getSerialNumber():myPriority.ordinal() - anotherPriority.ordinal();
  }

  public static interface RequestListener {
    public void onComplete(int setCode,T response,String errMsg);
  }
}

如果返回数据格式是Json,构建一个子类叫JsonRequest:

public class JsonRequest exteds Request {
  public JsonRequest(HttpMethod method,String url,RequestListener listener) {
      super(method,url,listener);
    }
   
  @Override
  public JSONObject parseresponse(Response response) {
    String jsonString = new String(response.getRawData());
    try {
      return nuw JSONObject(jsonString);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }
}

你可能感兴趣的:(13.网络框架的实现)