XUtils3代码详解--http

这是xutils3 源码分析的第二篇。

第一篇超级传送门:xutils3详解一


官方访问网络用法:

复杂版本:

/** 
* 自定义实体参数类请参考: 
* 请求注解 {@link org.xutils.http.annotation.HttpRequest} 
* 请求注解处理模板接口 {@link org.xutils.http.app.ParamsBuilder} 
* * 需要自定义类型作为callback的泛型时, 参考: 
* 响应注解 {@link org.xutils.http.annotation.HttpResponse} 
* 响应注解处理模板接口 {@link org.xutils.http.app.ResponseParser} 
* * 示例: 查看 org.xutils.sample.http 包里的代码 
*/
BaiduParams params =newBaiduParams();
params.wd ="xUtils";// 有上传文件时使用multipart表单, 否则上传原始文件流.
// params.setMultipart(true);// 上传文件方式 1
// params.uploadFile = new File("/sdcard/test.txt");// 上传文件方式 2
// params.addBodyParameter("uploadFile", new File("/sdcard/test.txt"));
Callback.Cancelable cancelable = x.http().get(params, 
/** * 1. callback的泛型: 
* callback参数默认支持的泛型类型参见{@link org.xutils.http.loader.LoaderFactory}, 
* 例如: 指定泛型为File则可实现文件下载, 使用params.setSaveFilePath(path)指定文件保存的全路径. 
* 默认支持断点续传(采用了文件锁和尾端校验续传文件的一致性). 
* 其他常用类型可以自己在LoaderFactory中注册, 
* 也可以使用{@link org.xutils.http.annotation.HttpResponse} 
* 将注解HttpResponse加到自定义返回值类型上, 实现自定义ResponseParser接口来统一转换. 
* 如果返回值是json形式, 那么利用第三方的json工具将十分容易定义自己的ResponseParser. 
* 如示例代码{@link org.xutils.sample.http.BaiduResponse}, 可直接使用BaiduResponse作为 
* callback的泛型. 
* * 2. callback的组合: 
* 可以用基类或接口组合个种类的Callback, 见{@link org.xutils.common.Callback}. 
* 例如: 
* a. 组合使用CacheCallback将使请求检测缓存或将结果存入缓存(仅GET请求生效). 
* b. 组合使用PrepareCallback的prepare方法将为callback提供一次后台执行耗时任务的机会, 
* 然后将结果给onCache或onSuccess. 
* c. 组合使用ProgressCallback将提供进度回调.
* ...(可参考{@link org.xutils.image.ImageLoader} 
* 或 示例代码中的 {@link org.xutils.sample.download.DownloadCallback}) 
* * 3. 请求过程拦截或记录日志: 参考 {@link org.xutils.http.app.RequestTracker} 
* * 4. 请求Header获取: 参考 {@link org.xutils.http.app.RequestInterceptListener} 
* * 5. 其他(线程池, 超时, 重定向, 重试, 代理等): 参考 {@link org.xutils.http.RequestParams} 
* 
**/
  newCallback.CommonCallback() { 
      @Override
      public void onSuccess(Stringresult) { 
        Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show(); 
      } 
      @Override
      public void onError(Throwableex, booleanisOnCallback) { 
          //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
          if (ex instanceofHttpException) { // 网络错误
              HttpException httpEx = (HttpException) ex; 
              int responseCode = httpEx.getCode(); 
              String responseMsg = httpEx.getMessage();
               String errorResult = httpEx.getResult();
               // ... 
          } else {
           // 其他错误//
             ... 
          } 
          Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show(); 
        } 
        @Override
        public void onCancelled(CancelledExceptioncex) { 
            Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
           }
     @Override
      public void onFinished() { } 
    });
// cancelable.cancel(); // 取消请求

简单版本:

RequestParams params =newRequestParams("https://www.baidu.com/s"); 
params.setSslSocketFactory(...); // 设置ssl 
params.addQueryStringParameter("wd", "xUtils"); 
x.http().get(params, newCallback.CommonCallback() { 
  @Override
  public void onSuccess(Stringresult) { 
  Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show(); 
  } 
  @Override
  public void onError(Throwableex, booleanisOnCallback) { 
  Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
  } 
  @Override
  public void onCancelled(CancelledExceptioncex) { 
  Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show(); 
  } 
  @Override
  public void onFinished() { }
 });
带有缓存的请求示例:
BaiduParams params =newBaiduParams();
params.wd ="xUtils";
// 默认缓存存活时间, 单位:毫秒.(如果服务没有返回有效的max-age或Expires)params.setCacheMaxAge(1000*60);
Callback.Cancelable cancelable // 使用CacheCallback, xUtils将为该请求缓存数据.
          = x.http().get(params, newCallback.CacheCallback() { 
          privateboolean hasError =false;
          privateString result =null; 
          @Override
          public boolean onCache(Stringresult) {
           // 得到缓存数据, 缓存过期后不会进入这个方法.
          // 如果服务端没有返回过期时间, 参考params.setCacheMaxAge(maxAge)方法.
           ////* 客户端会根据服务端返回的 header 中 max-age 或 expires 来确定本地缓存是否给 onCache 方法.
          // 如果服务端没有返回 max-age 或 expires, 那么缓存将一直保存, 除非这里自己定义了返回false的
        // 逻辑, 那么xUtils将请求新数据, 来覆盖它.
        //// * 如果信任该缓存返回 true, 将不再请求网络;
        // 返回 false 继续请求网络, 但会在请求头中加上ETag, Last-Modified等信息,
        // 如果服务端返回304, 则表示数据没有更新, 不继续加载数据.
        //this.result = result; returnfalse;   
          // true: 信任缓存数据, 不在发起网络请求; false不信任缓存数据.
        } 
        @Override
        public void onSuccess(Stringresult) { 
          // 注意: 如果服务返回304或 onCache 选择了信任缓存, 这里将不会被调用,
          // 但是 onFinished 总会被调用.
          this.result = result; 
        } 
        @Override
        public void onError(Throwableex, booleanisOnCallback) {
         hasError =true;
         Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
         if (ex instanceofHttpException) {
             // 网络错误
            HttpException httpEx = (HttpException) ex;
             int responseCode = httpEx.getCode();
             String responseMsg = httpEx.getMessage();
             String errorResult = httpEx.getResult();
         // ... 
        } else {  
       // 其他错误
        // ...
         }
     }
       @Override
        public void onCancelled(CancelledExceptioncex) {   
            Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
        }
       @Override
        public void onFinished() {
             if (!hasError && result !=null) {
               // 成功获取数据
              Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
               }
         }
    });


源码查看:

首先还是入口:http相关的接口和实现类。HttpManager和HttpManagerImpl
接口很简单。定义了三个异步请求和四个同步请求的方法签名。

/** 
* Created by wyouflf on 15/6/17. 
* http请求接口
*/
public interface HttpManager {
/** * 异步GET请求*/
 Callback.Cancelable get(RequestParams entity, Callback.CommonCallback callback);
/** * 异步POST请求*/
 Callback.Cancelable post(RequestParams entity, Callback.CommonCallback callback);
/** * 异步请求*/
 Callback.Cancelable request(HttpMethod method, RequestParams entity, Callback.CommonCallback callback);
/** * 同步GET请求*/
 T getSync(RequestParams entity, Class resultType) throws Throwable;
/** * 同步POST请求 */
 T postSync(RequestParams entity, Class resultType) throws Throwable;
/** * 同步请求 */
 T requestSync(HttpMethod method, RequestParams entity, Class resultType) throws Throwable;
/** * 同步请求 */
 T requestSync(HttpMethod method, RequestParams entity, Callback.TypedCallback callback) throws Throwable;
}

先看异步的一些实现方法:
HttpManagerImpl: 看源码我们得知。异步请求最后都会调用到这个方法:request(···)。在这个方法中发现 会new一个HttpTask 并放到线程池中运行。在上一篇博客可以知道 x.task().start(task) 其实就是调用task的doBackground方法。

@Override
public  Callback.Cancelable request(HttpMethod method, RequestParams entity, Callback.CommonCallback callback) { 
entity.setMethod(method);
Callback.Cancelable cancelable = null;
 if (callback instanceof Callback.Cancelable) {
 cancelable = (Callback.Cancelable) callback;
} 
HttpTask task = new HttpTask(entity, cancelable, callback); 
return x.task().start(task);
}

我们继续跟进来查看HttpTask:* 我们发现httpTask 中有哦很多成员变量。 作者代码注释的也比较清楚。


/** 
* Created by wyouflf on 15/7/23. 
* http 请求任务
*/
public class HttpTask extends AbsTask implements ProgressHandler {// 请求相关
private RequestParams params;
private UriRequest request;
private RequestWorker requestWorker;
private final Executor executor;
private final Callback.CommonCallback callback;
// 缓存控制
private Object rawResult = null;
private final Object cacheLock = new Object();
private volatile Boolean trustCache = null;
// 扩展callback
private Callback.CacheCallback cacheCallback;
private Callback.PrepareCallback prepareCallback;
private Callback.ProgressCallback progressCallback;
private RequestInterceptListener requestInterceptListener;
// 文件下载线程数限制
private Type loadType;
private final static int MAX_FILE_LOAD_WORKER = 3;
private final static AtomicInteger sCurrFileLoadCount = new AtomicInteger(0);
// 文件下载任务
private static final HashMap>>DOWNLOAD_TASK = new HashMap>>(1);
private static final PriorityExecutor HTTP_EXECUTOR = new PriorityExecutor(5, true);
private static final PriorityExecutor CACHE_EXECUTOR = new PriorityExecutor(5, true);
}
  • HttpTask构造函数中,先用了两个断言来确保params 和callback 不为空。并赋值给成员变量。 判断是哪个callback 并赋值给想应的callback。初始化tracker 日志跟踪系统。初始化线程池 executor.
public HttpTask(RequestParams params, Callback.Cancelable cancelHandler, Callback.CommonCallback callback) { 
super(cancelHandler);
 assert params != null;
 assert callback != null;
 // set params & callback
 this.params = params;
 this.callback = callback;
 if (callback instanceof Callback.CacheCallback) {
 this.cacheCallback = (Callback.CacheCallback) callback;
 } 
if (callback instanceof Callback.PrepareCallback) { 
this.prepareCallback = (Callback.PrepareCallback) callback;
 }
 if (callback instanceof Callback.ProgressCallback) { 
this.progressCallback = (Callback.ProgressCallback) callback; 
} 
if (callback instanceof RequestInterceptListener) { 
this.requestInterceptListener = (RequestInterceptListener) callback;
 } 
// init tracker {
 RequestTracker customTracker = params.getRequestTracker();
 if (customTracker == null) {
 if (callback instanceof RequestTracker) {
customTracker = (RequestTracker) callback;
 } else {
 customTracker = UriRequestFactory.getDefaultTracker();
 } 
}
 if (customTracker != null) {
 tracker = new RequestTrackerWrapper(customTracker);
 } 
}
 // init executor
 if (params.getExecutor() != null) {
 this.executor = params.getExecutor();
 } else { 
if (cacheCallback != null) {
 this.executor = CACHE_EXECUTOR;
} else { 
this.executor = HTTP_EXECUTOR;
 } 
}
}
  • doBackground 方法: 异步请求的最主要的方法。 我把这个方法截断了。 这部分主要是做一些准备工作。比如说 初始化,缓存等。
@Override
@SuppressWarnings("unchecked")
protected ResultType doBackground() throws Throwable {
 if (this.isCancelled()) {
  throw new Callback.CancelledException("cancelled before request");
 }
 // 初始化请求参数 
 ResultType result = null; 
 resolveLoadType();
 request = createNewRequest();
 checkDownloadTask();
 // retry 初始化
 boolean retry = true;
 int retryCount = 0;
 Throwable exception = null;
 HttpRetryHandler retryHandler = this.params.getHttpRetryHandler();
 if (retryHandler == null) {
  retryHandler = new HttpRetryHandler();
  }
 retryHandler.setMaxRetryCount(this.params.getMaxRetryCount());
 if (this.isCancelled()) {
  throw new Callback.CancelledException("cancelled before request"); 
 } 
 // 检查缓存
 Object cacheResult = null;
 if (cacheCallback != null && HttpMethod.permitsCache(params.getMethod())) { 
 // 尝试从缓存获取结果, 并为请求头加入缓存控制参数.
 try {
  clearRawResult(); LogUtil.d("load cache: " + this.request.getRequestUri());
 rawResult = this.request.loadResultFromCache();
  } catch (Throwable ex) {
  LogUtil.w("load disk cache error", ex);

 }
  if (this.isCancelled()) {
 clearRawResult();
 throw new Callback.CancelledException("cancelled before request");
 }
  if (rawResult != null) {
    if (prepareCallback != null) {
      try {
         cacheResult = prepareCallback.prepare(rawResult);
       } catch (Throwable ex) {
         cacheResult = null;
         LogUtil.w("prepare disk cache error", ex);
       } finally {
          clearRawResult();
       }
     } else {
     cacheResult = rawResult;   
  }
   if (this.isCancelled()) {
     throw new Callback.CancelledException("cancelled before request");
    } 
    if (cacheResult != null) {
       // 同步等待是否信任缓存
       this.update(FLAG_CACHE, cacheResult); 
        while (trustCache == null) {
             synchronized (cacheLock) {
                       try {
                                 cacheLock.wait();
                              } catch (Throwable ignored) {
                               }
             }
           } 
        // 处理完成 
      if (trustCache) {
             return null;
       }
     }
    }
  } 
  if (trustCache == null) {
       trustCache = false;
     } 
  if (cacheResult == null) {
     this.request.clearCacheHeader();
   }
  • 发请求的代码: 请求代码中主要就是重试机子和发送机制。字段retry 是控制重试的开关。请求正常则retry一直为false。否则异常处理代码块里编写有重试的规则。在代码里面发送请求的是对象RequestWorker的run();方法。所有我们去看看RequestWorker对象。
 // 发起请求
 retry = true;
 while (retry) {
   retry = false;
   try {
       if (this.isCancelled()) {
         throw new Callback.CancelledException("cancelled before request");
         } 
      // 由loader发起请求, 拿到结果. 
      this.request.close(); 
      // retry 前关闭上次请求 
      try {
           clearRawResult();
           // 开始请求工作 
            LogUtil.d("load: " + this.request.getRequestUri()); 
            requestWorker = new RequestWorker();
           if (params.isCancelFast()) {
               requestWorker.start();
               requestWorker.join();
            } else {
            requestWorker.run();
           } 
          if (requestWorker.ex != null) {
                   throw requestWorker.ex;
          }
         rawResult = requestWorker.result;
         } catch (Throwable ex) {
           clearRawResult();
           if (this.isCancelled()) {
               throw new Callback.CancelledException("cancelled during request");
             } else {
           throw ex;
           }
       }
       if (prepareCallback != null) { 
          if (this.isCancelled()) { 
                  throw new Callback.CancelledException("cancelled before request");
           }
         try {
             result = (ResultType) prepareCallback.prepare(rawResult);
         } finally {
           clearRawResult();
         } 
        } else { 
          result = (ResultType) rawResult;
        }
         // 保存缓存 
        if (cacheCallback != null && HttpMethod.permitsCache(params.getMethod())) {
           this.request.save2Cache();
         }
        if (this.isCancelled()) { 
              throw new Callback.CancelledException("cancelled after request");
         }
       } catch (HttpRedirectException redirectEx) {
             retry = true;
              LogUtil.w("Http Redirect:" + params.getUri());
       } catch (Throwable ex) {
           if (this.request.getResponseCode() == 304) {
             // disk cache is valid.
             return null;
           } else {
           exception = ex;
           if (this.isCancelled() && !(exception instanceof Callback.CancelledException)) {
               exception = new Callback.CancelledException("canceled by user");
             }
           retry = retryHandler.retryRequest(exception, ++retryCount, this.request);
           }
          } 
        } 
      if (exception != null && result == null && !trustCache) {
             throw exception; 
      } 
      return result;
  }
  • RequestWorker: 是HttpTask的内部类 ,主要的功能是请求发送和加载数据线程. 内部run()方法分析:
    • 下载另作处理
    • 请求前回调 requestInterceptListener.beforeRequest(request);
    • 请求 this.result = request.loadResult(); 得到结果
    • 请求后回调 requestInterceptListener.afterRequest(request);
    • http重定向类的异常处理。
/** 
* 请求发送和加载数据线程. 
* 该线程被join到HttpTask的工作线程去执行. 
* 它的主要作用是为了能强行中断请求的链接过程; 
* 并辅助限制同时下载文件的线程数. 
* but: 
* 创建一个Thread约耗时2毫秒, 优化? 
*/
private final class RequestWorker extends Thread { 
 /*private*/ Object result;
 /*private*/ Throwable ex;
 private RequestWorker() { }
 public void run() { 
    try {
       if (File.class == loadType) {
           while (sCurrFileLoadCount.get() >= MAX_FILE_LOAD_WORKER && !HttpTask.this.isCancelled()) {
             synchronized (sCurrFileLoadCount) {
                 try {
                     sCurrFileLoadCount.wait(100);
                      } catch (Throwable ignored) { }
                 } 
              }
           sCurrFileLoadCount.incrementAndGet();
           }
         if (HttpTask.this.isCancelled()) {
               throw new Callback.CancelledException("cancelled before request");
           }
         // intercept response 
        if (requestInterceptListener != null) { 
              requestInterceptListener.beforeRequest(request);
         }
         try {
             this.result = request.loadResult();
           } catch (Throwable ex) {
               this.ex = ex;
           } 
        // intercept response
       if (requestInterceptListener != null) { 
              requestInterceptListener.afterRequest(request);
         }
       if (this.ex != null) {
             throw this.ex;
         } 
      } catch (Throwable ex) {
           this.ex = ex;
           if (ex instanceof HttpException) {
                 HttpException httpEx = (HttpException) ex;
                 int errorCode = httpEx.getCode();
                 if (errorCode == 301 || errorCode == 302) {
                       RedirectHandler redirectHandler = params.getRedirectHandler();
                       if (redirectHandler != null) {
                           try {
                                 RequestParams redirectParams = redirectHandler.getRedirectParams(request);
                                 if (redirectParams != null) {
                                   if (redirectParams.getMethod() == null) { 
                                        redirectParams.setMethod(params.getMethod());
                                     }
                                 // 开始重定向请求
                                 HttpTask.this.params = redirectParams;
                                 HttpTask.this.request = createNewRequest(); 
                                 this.ex = new HttpRedirectException(errorCode, httpEx.getMessage(), httpEx.getResult());
                               }
                               } catch (Throwable throwable) {
                                                    this.ex = ex; 
                               } 
                            } 
                          } 
                        } 
                      } finally {
                          if (File.class == loadType) {
                             synchronized (sCurrFileLoadCount) { 
                                          sCurrFileLoadCount.decrementAndGet();   
                                          sCurrFileLoadCount.notifyAll();
                               } 
                            }
                         } 
  }
}

同步的一些实现方法:

  • **HttpManagerImpl: ** 最终都会内部调用到requestSync(···)的方法。 在这个方法中 我们可以发现 。作者也创建了一个HttpTask。并调用了x.task().startSync(task);的方法。这个方法我们task的实现类发现实际调用的是 TaskControllerImpl.startSync( AbsTask task)
Override 
public  T getSync(RequestParams entity, Class resultType) throws Throwable {
   return requestSync(HttpMethod.GET, entity, resultType);
  }
@Override
 public  T postSync(RequestParams entity, Class resultType) throws Throwable {
 return requestSync(HttpMethod.POST, entity, resultType);
}
@Override
public  T requestSync(HttpMethod method, RequestParams entity, Class resultType) throws Throwable {
 DefaultSyncCallback callback = new DefaultSyncCallback(resultType);
 return requestSync(method, entity, callback);
}
@Override
public  T requestSync(HttpMethod method, RequestParams entity, Callback.TypedCallback callback) throws Throwable { 
entity.setMethod(method);
 HttpTask task = new HttpTask(entity, null, callback);
 return x.task().startSync(task);
}

  • TaskControllerImpl.startSync( AbsTask task) 找到这个方法我们发现 调用的是AbsTask的四个方法。onWaiting onStarted doBackground onSuccess 我们知道其实就是httpTask的这个四个方法。通过字面意思我们也可以知道就是 等待,开始,子线程运行和成功四个方法。
@Override
public  T startSync(AbsTask task) throws Throwable {
 T result = null;
 try {
   task.onWaiting();
   task.onStarted();
   result = task.doBackground();
   task.onSuccess(result);
   } catch (Callback.CancelledException cex) {
       task.onCancelled(cex);
   } catch (Throwable ex) { 
        task.onError(ex, false);
         throw ex;
   } finally {
       task.onFinished();
   }
 return result;
}
  • HttpTask的这四个方法: 在onSuccess方法中出现一个callback。回溯到TaskControllerImpl,我们发现了这个callback。它为外部传递的。外部没有传递的化。有个默认的DefaultSyncCallback。
@Override
protected void onWaiting() { 
  if (tracker != null) {
     tracker.onWaiting(params);
   }
 if (progressCallback != null) {
     progressCallback.onWaiting();
   }
}
@Override
protected void onStarted() {
   if (tracker != null) {
     tracker.onStart(params);
   }
   if (progressCallback != null) {
       progressCallback.onStarted();
   }
}
@Override
protected void onSuccess(ResultType result) {
   if (tracker != null) {
       tracker.onSuccess(request, result);
    }
   if (result != null) {
     callback.onSuccess(result);
    }
}
  • DefaultSyncCallback: 此对象传递一个泛型。此泛型就为onSuccess 中返回的结果。 需要再构建DefaultSyncCallback对象时候传递。
private class DefaultSyncCallback implements Callback.TypedCallback {
 private final Class resultType;
 public DefaultSyncCallback(Class resultType) {
 this.resultType = resultType;
 }
 @Override
 public Type getLoadType() {
   return resultType;
   }
 @Override
 public void onSuccess(T result) { }
 @Override
 public void onError(Throwable ex, boolean isOnCallback) { } 
@Override
 public void onCancelled(CancelledException cex) { }
 @Override
 public void onFinished() { }
}

从task的onwaiting 可以得到。同步请求会一直等待 直到请求返回 或者请求超时。

你可能感兴趣的:(XUtils3代码详解--http)