网络访问框架源码分析--待完善
2016-08-19 09:29
417 查看
1:做过项目中用到的开源框架
{1}:开源框架:xuitls;uil;volley
xutils----httputils;dbutils;viewutils;bitmaputils
httputil源码分析:大致总体设计
相关的类图:
源码执行历程:
httpUtils执行HttpHandler<T> sendRequest(HttpRequest request, RequestParams params, RequestCallBack<T> callBack)
1:httpHandler.executeOnExcutor();//调用异步任务的执行onpreExecute();
2:exec.excute(futureTask)-->mworker:postResult(doInBackground(mParams))
3:doInbackGround():publishProgress();responseInfo=sendRequest(HttpRequest
request);
4:publishProgress--->sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
5:在handleMessage中调用onProgressUpdate();
protected void onProgressUpdate(Object... values) {
if (this.state == State.CANCELLED || values == null || values.length == 0 || callback == null) return;
switch ((Integer) values[0]) {
case UPDATE_START:
this.state = State.STARTED;
callback.onStart();
break;
case UPDATE_LOADING:
if (values.length != 3) return;
this.state = State.LOADING;
callback.onLoading(
Long.valueOf(String.valueOf(values[1])),
Long.valueOf(String.valueOf(values[2])),
isUploading);
break;
case UPDATE_FAILURE:
if (values.length != 3) return;
this.state = State.FAILURE;
callback.onFailure((HttpException) values[1], (String) values[2]);
break;
case UPDATE_SUCCESS:
if (values.length != 2) return;
this.state = State.SUCCESS;
callback.onSuccess((ResponseInfo<T>) values[1]);
break;
default:
break;
}
}
6:sendRequest()
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {
HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
while (true) {
if (autoResume && isDownloadingFile) {
File downloadFile = new File(fileSavePath);
long fileLen = 0;
if (downloadFile.isFile() && downloadFile.exists()) {
fileLen = downloadFile.length();
}
if (fileLen > 0) {
request.setHeader("RANGE", "bytes=" + fileLen + "-");
}
}
boolean retry = true;
IOException exception = null;
try {
requestMethod = request.getMethod();
if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
String result = HttpUtils.sHttpCache.get(requestUrl);
if (result != null) {
return new ResponseInfo<T>(null, (T) result, true);
}
}
ResponseInfo<T> responseInfo = null;
if (!isCancelled()) {
HttpResponse response = client.execute(request, context);
responseInfo = handleResponse(response);
}
return responseInfo;
} catch (UnknownHostException e) {
exception = e;
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (IOException e) {
exception = e;
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (NullPointerException e) {
exception = new IOException(e.getMessage());
exception.initCause(e);
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (HttpException e) {
throw e;
} catch (Throwable e) {
exception = new IOException(e.getMessage());
exception.initCause(e);
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
}
if (!retry) {
throw new HttpException(exception);
}
}
}
7:handleResponse();解析response获取的entity数据用FileDownLoadHandler或StringDownloadHandler解析获取数据;
8:handleEntity();--->updateProgress()--->publishProgress()-->sendMessage()---->onProgressUpdate()--->UPDATE_LOADING;
9:回到handleResponse();---->mFutureTask.done()---->postResult()-->sendMessage()---->onProgressUpdate()--->MESSAGE_POST_RESULT;
1.2:volley的源码分析
1. Volley特点
(1) 特别适合数据量小,通信频繁的网络操作。
(2) 扩展性强。Volley 中大多是基于接口的设计,可根据需要自行定制。
(3) 一定程度符合 Http 规范,包括返回 ResponseCode(2xx、3xx、4xx、5xx)的处理,请求头的处理, 缓存机制的支持等。并支持重试及优先级定义。
(4) 提供简便的图片加载工具
2. 概念介绍
Request:表示一个请求的抽象类。StringRequest、JsonRequest、ImageRequest 都是它的子类,表示某种类型的请求。我们还可以继承于它,实现自定义的Request。
RequestQueue:表示请求队列,里面包含一个CacheDispatcher(用于处理缓存请求的线程)、NetworkDispatcher数组(用于处理网络请求的调度线程,默认长度为4),一个
ResponseDelivery(返回结果分发)。通过start() 函数启动时会启动CacheDispatcher和NetworkDispatcher。
CacheDispatcher:一个线程,用于调度处理缓存的请求。启动后会不断从缓存请求队列中取请求处理,队列为空则等待,请求处理结束则将结果传递给ResponseDelivery去执行后续处理。当结果未缓存过、缓存失效或缓存需要刷新的情况下,该请求都需要重新进入NetworkDispatcher去调度处理。
NetworkDispatcher:一个线程,用于调度处理走网络的请求。启动后会不断从网络请求队列中取请求处理,队列为空则等待,请求处理结束则将结果传递给ResponseDelivery去执行后续处理,并判断结果是否要进行缓存。
ResponseDelivery:返回结果分发接口,目前只有基于ExecutorDelivery的在传入的handler对应线程内进行分发。
HttpStack:处理 Http 请求,返回请求结果。目前 Volley 中有基于HttpURLConnection 的HurlStack和 基于 Apache HttpClient 的HttpClientStack。
Network:调用HttpStack处理请求,并将结果转换为可被ResponseDelivery处理的NetworkResponse。
Cache:缓存请求结果,Volley 默认使用的是基于 sdcard 的DiskBasedCache。NetworkDispatcher得到请求结果后判断是否需要存储在 Cache,CacheDispatcher会从 Cache 中取缓存结果。
UIL:图片加载工具
2:SlideMenue_library开源控件的源码分析
{1}:开源框架:xuitls;uil;volley
xutils----httputils;dbutils;viewutils;bitmaputils
httputil源码分析:大致总体设计
相关的类图:
源码执行历程:
httpUtils执行HttpHandler<T> sendRequest(HttpRequest request, RequestParams params, RequestCallBack<T> callBack)
1:httpHandler.executeOnExcutor();//调用异步任务的执行onpreExecute();
2:exec.excute(futureTask)-->mworker:postResult(doInBackground(mParams))
3:doInbackGround():publishProgress();responseInfo=sendRequest(HttpRequest
request);
4:publishProgress--->sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
5:在handleMessage中调用onProgressUpdate();
protected void onProgressUpdate(Object... values) {
if (this.state == State.CANCELLED || values == null || values.length == 0 || callback == null) return;
switch ((Integer) values[0]) {
case UPDATE_START:
this.state = State.STARTED;
callback.onStart();
break;
case UPDATE_LOADING:
if (values.length != 3) return;
this.state = State.LOADING;
callback.onLoading(
Long.valueOf(String.valueOf(values[1])),
Long.valueOf(String.valueOf(values[2])),
isUploading);
break;
case UPDATE_FAILURE:
if (values.length != 3) return;
this.state = State.FAILURE;
callback.onFailure((HttpException) values[1], (String) values[2]);
break;
case UPDATE_SUCCESS:
if (values.length != 2) return;
this.state = State.SUCCESS;
callback.onSuccess((ResponseInfo<T>) values[1]);
break;
default:
break;
}
}
6:sendRequest()
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {
HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
while (true) {
if (autoResume && isDownloadingFile) {
File downloadFile = new File(fileSavePath);
long fileLen = 0;
if (downloadFile.isFile() && downloadFile.exists()) {
fileLen = downloadFile.length();
}
if (fileLen > 0) {
request.setHeader("RANGE", "bytes=" + fileLen + "-");
}
}
boolean retry = true;
IOException exception = null;
try {
requestMethod = request.getMethod();
if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
String result = HttpUtils.sHttpCache.get(requestUrl);
if (result != null) {
return new ResponseInfo<T>(null, (T) result, true);
}
}
ResponseInfo<T> responseInfo = null;
if (!isCancelled()) {
HttpResponse response = client.execute(request, context);
responseInfo = handleResponse(response);
}
return responseInfo;
} catch (UnknownHostException e) {
exception = e;
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (IOException e) {
exception = e;
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (NullPointerException e) {
exception = new IOException(e.getMessage());
exception.initCause(e);
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
} catch (HttpException e) {
throw e;
} catch (Throwable e) {
exception = new IOException(e.getMessage());
exception.initCause(e);
retry = retryHandler.retryRequest(exception, ++retriedCount, context);
}
if (!retry) {
throw new HttpException(exception);
}
}
}
7:handleResponse();解析response获取的entity数据用FileDownLoadHandler或StringDownloadHandler解析获取数据;
8:handleEntity();--->updateProgress()--->publishProgress()-->sendMessage()---->onProgressUpdate()--->UPDATE_LOADING;
9:回到handleResponse();---->mFutureTask.done()---->postResult()-->sendMessage()---->onProgressUpdate()--->MESSAGE_POST_RESULT;
1.2:volley的源码分析
1. Volley特点
(1) 特别适合数据量小,通信频繁的网络操作。
(2) 扩展性强。Volley 中大多是基于接口的设计,可根据需要自行定制。
(3) 一定程度符合 Http 规范,包括返回 ResponseCode(2xx、3xx、4xx、5xx)的处理,请求头的处理, 缓存机制的支持等。并支持重试及优先级定义。
(4) 提供简便的图片加载工具
2. 概念介绍
Request:表示一个请求的抽象类。StringRequest、JsonRequest、ImageRequest 都是它的子类,表示某种类型的请求。我们还可以继承于它,实现自定义的Request。
RequestQueue:表示请求队列,里面包含一个CacheDispatcher(用于处理缓存请求的线程)、NetworkDispatcher数组(用于处理网络请求的调度线程,默认长度为4),一个
ResponseDelivery(返回结果分发)。通过start() 函数启动时会启动CacheDispatcher和NetworkDispatcher。
CacheDispatcher:一个线程,用于调度处理缓存的请求。启动后会不断从缓存请求队列中取请求处理,队列为空则等待,请求处理结束则将结果传递给ResponseDelivery去执行后续处理。当结果未缓存过、缓存失效或缓存需要刷新的情况下,该请求都需要重新进入NetworkDispatcher去调度处理。
NetworkDispatcher:一个线程,用于调度处理走网络的请求。启动后会不断从网络请求队列中取请求处理,队列为空则等待,请求处理结束则将结果传递给ResponseDelivery去执行后续处理,并判断结果是否要进行缓存。
ResponseDelivery:返回结果分发接口,目前只有基于ExecutorDelivery的在传入的handler对应线程内进行分发。
HttpStack:处理 Http 请求,返回请求结果。目前 Volley 中有基于HttpURLConnection 的HurlStack和 基于 Apache HttpClient 的HttpClientStack。
Network:调用HttpStack处理请求,并将结果转换为可被ResponseDelivery处理的NetworkResponse。
Cache:缓存请求结果,Volley 默认使用的是基于 sdcard 的DiskBasedCache。NetworkDispatcher得到请求结果后判断是否需要存储在 Cache,CacheDispatcher会从 Cache 中取缓存结果。
UIL:图片加载工具
2:SlideMenue_library开源控件的源码分析
相关文章推荐
- Linux系统开发10 Socket API编程1 大端小端 TCP模型
- System.Web.HttpContext.Current.Session为NULL解决方法
- Volley的网络请求内存溢出
- netstat -anu|grep 69命令详解
- HTTP协议由浅入深
- 【前端安全】JavaScript防http劫持与XSS 转
- C#网络编程概述
- http://blog.chinaunix.net/uid-21411227-id-1826986.html
- Neutron 网络基本概念 - 每天5分钟玩转 OpenStack(66)
- 记网络HTTP学习心得
- 科技部:“网络空间安全”重点专项 2017年度项目申报指南建议
- webapi使用System.Web.Http.Cors配置跨域访问的几点注意事项
- HttpGet和HttpPost处理重定向的区别
- python网络编程
- SSL在https和MySQL中的原理思考
- ---使用HttpSession实现验证码功能
- http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.htm ASP.NET从零开始学习EF的增删改查
- http协议
- HTTP协议中GET、POST和HEAD的区别?
- Unix网络编程读书笔记(一)