android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件
网络请求是全部App都不可缺少的功能,假设每次开发都重写一次网络请求或者将曾经的代码拷贝到新的App中,不是非常合理,出于此目的,我希望将整个网络请求框架独立出来,与业务逻辑分隔开,这样就能够避免每次都要又一次编写网络请求,于是基于我比較熟悉的asynchttpclient又一次二次封装了一个网络请求框架。
思路:网络请求层唯一的功能就是发送请求,接收响应数据,请求取消,cookie处理这几个功能,二次助封装后这些功能能够直接调用封装好的方法就可以。
二次助封装代码例如以下:
1.功能接口:
/**********************************************************
* @文件名:DisposeDataListener.java
* @文件作者:rzq
* @创建时间:2015年8月19日 上午11:01:13
* @文件描写叙述:
* @改动历史:2015年8月19日创建初始版本号
**********************************************************/
public interface DisposeDataListener
{
/**
* 请求開始回调事件处理
*/
public void onStart(); /**
* 请求成功回调事件处理
*/
public void onSuccess(Object responseObj); /**
* 请求失败回调事件处理
*/
public void onFailure(Object reasonObj); /**
* 请求重连回调事件处理
*/
public void onRetry(int retryNo); /**
* 请求进度回调事件处理
*/
public void onProgress(long bytesWritten, long totalSize); /**
* 请求结束回调事件处理
*/
public void onFinish(); /**
* 请求取消回调事件处理
*/
public void onCancel();
}
2.请求功能接口适配器模式
public class DisposeDataHandle implements DisposeDataListener
{
@Override
public void onStart()
{
} @Override
public void onSuccess(Object responseObj)
{
} @Override
public void onFailure(Object reasonObj)
{
} @Override
public void onRetry(int retryNo)
{
} @Override
public void onProgress(long bytesWritten, long totalSize)
{
} @Override
public void onFinish()
{
} @Override
public void onCancel()
{
}
}
3.请求回调事件处理:
/**********************************************************
* @文件名:BaseJsonResponseHandler.java
* @文件作者:rzq
* @创建时间:2015年8月19日 上午10:41:46
* @文件描写叙述:服务器Response基础类,包含了java层异常和业务逻辑层异常码定义
* @改动历史:2015年8月19日创建初始版本号
**********************************************************/
public class BaseJsonResponseHandler extends JsonHttpResponseHandler
{
/**
* the logic layer exception, may alter in different app
*/
protected final String RESULT_CODE = "ecode";
protected final int RESULT_CODE_VALUE = 0;
protected final String ERROR_MSG = "emsg";
protected final String EMPTY_MSG = ""; /**
* the java layer exception
*/
protected final int NETWORK_ERROR = -1; // the network relative error
protected final int JSON_ERROR = -2; // the JSON relative error
protected final int OTHER_ERROR = -3; // the unknow error /**
* interface and the handle class
*/
protected Class<?> mClass;
protected DisposeDataHandle mDataHandle; public BaseJsonResponseHandler(DisposeDataHandle dataHandle, Class<?> clazz)
{
this.mDataHandle = dataHandle;
this.mClass = clazz;
} public BaseJsonResponseHandler(DisposeDataHandle dataHandle)
{
this.mDataHandle = dataHandle;
} /**
* only handle the success branch(ecode == 0)
*/
public void onSuccess(JSONObject response)
{
} /**
* handle the java exception and logic exception branch(ecode != 0)
*/
public void onFailure(Throwable throwObj)
{
} @Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
onSuccess(response);
} @Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
{
onFailure(throwable);
}
} /**********************************************************
* @文件名:CommonJsonResponseHandler.java
* @文件作者:rzq
* @创建时间:2015年8月19日 上午11:01:13
* @文件描写叙述:业务逻辑层真正处理的地方,包含java层异常和业务层异常
* @改动历史:2015年8月19日创建初始版本号
**********************************************************/
public class CommonJsonResponseHandler extends BaseJsonResponseHandler
{
public CommonJsonResponseHandler(DisposeDataHandle dataHandle)
{
super(dataHandle);
} public CommonJsonResponseHandler(DisposeDataHandle dataHandle, Class<? > clazz)
{
super(dataHandle, clazz);
} @Override
public void onStart()
{
mDataHandle.onStart();
} @Override
public void onProgress(long bytesWritten, long totalSize)
{
mDataHandle.onProgress(bytesWritten, totalSize);
} @Override
public void onSuccess(JSONObject response)
{
handleResponse(response);
} @Override
public void onFailure(Throwable throwObj)
{
mDataHandle.onFailure(new LogicException(NETWORK_ERROR, throwObj.getMessage()));
} @Override
public void onCancel()
{
mDataHandle.onCancel();
} @Override
public void onRetry(int retryNo)
{
mDataHandle.onRetry(retryNo);
} @Override
public void onFinish()
{
mDataHandle.onFinish();
} /**
* handle the server response
*/
private void handleResponse(JSONObject response)
{
if (response == null)
{
mDataHandle.onFailure(new LogicException(NETWORK_ERROR, EMPTY_MSG));
return;
} try
{
if (response.has(RESULT_CODE))
{
if (response.optInt(RESULT_CODE) == RESULT_CODE_VALUE)
{
if (mClass == null)
{
mDataHandle.onSuccess(response);
}
else
{
Object obj = ResponseEntityToModule.parseJsonObjectToModule(response, mClass);
if (obj != null)
{
mDataHandle.onSuccess(obj);
}
else
{
mDataHandle.onFailure(new LogicException(JSON_ERROR, EMPTY_MSG));
}
}
}
else
{
if (response.has(ERROR_MSG))
{
mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), response
.optString(ERROR_MSG)));
}
else
{
mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), EMPTY_MSG));
}
}
}
else
{
if (response.has(ERROR_MSG))
{
mDataHandle.onFailure(new LogicException(OTHER_ERROR, response.optString(ERROR_MSG)));
}
}
}
catch (Exception e)
{
mDataHandle.onFailure(new LogicException(OTHER_ERROR, e.getMessage()));
e.printStackTrace();
}
}
}
4.自己定义异常类,对java异常和业务逻辑异常封装统一处理
/**********************************************************
* @文件名:LogicException.java
* @文件作者:rzq
* @创建时间:2015年8月19日 上午10:05:08
* @文件描写叙述:自己定义异常类,返回ecode,emsg到业务层
* @改动历史:2015年8月19日创建初始版本号
**********************************************************/
public class LogicException extends Exception
{
private static final long serialVersionUID = 1L; /**
* the server return code
*/
private int ecode; /**
* the server return error message
*/
private String emsg; public LogicException(int ecode, String emsg)
{
this.ecode = ecode;
this.emsg = emsg;
} public int getEcode()
{
return ecode;
} public String getEmsg()
{
return emsg;
}
}
5.请求发送入口类CommonClient:
/**********************************************************
* @文件名:CommonClient.java
* @文件作者:rzq
* @创建时间:2015年8月19日 上午11:38:57
* @文件描写叙述:通用httpclient,支持重连,取消请求,Cookie存储
* @改动历史:2015年8月19日创建初始版本号
**********************************************************/
public class CommonClient
{
private static AsyncHttpClient client;
static
{
/**
* init the retry exception
*/
AsyncHttpClient.allowRetryExceptionClass(IOException.class);
AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class);
AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class);
/**
* init the block retry exception
*/
AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class);
AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); client = new AsyncHttpClient();
} public static RequestHandle get(String url, AsyncHttpResponseHandler responseHandler)
{
return client.get(url, responseHandler);
} public static RequestHandle get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
{
return client.get(url, params, responseHandler);
} public static RequestHandle get(Context context, String url, AsyncHttpResponseHandler responseHandler)
{
return client.get(context, url, responseHandler);
} public static RequestHandle get(Context context, String url, RequestParams params,
AsyncHttpResponseHandler responseHandler)
{
return client.get(context, url, params, responseHandler);
} public static RequestHandle get(Context context, String url, Header[] headers, RequestParams params,
AsyncHttpResponseHandler responseHandler)
{
return client.get(context, url, headers, params, responseHandler);
} public static RequestHandle post(String url, AsyncHttpResponseHandler responseHandler)
{
return client.post(url, responseHandler);
} public static RequestHandle post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
{
return client.post(url, params, responseHandler);
} public static RequestHandle post(Context context, String url, RequestParams params,
AsyncHttpResponseHandler responseHandler)
{
return client.post(context, url, params, responseHandler);
} public static RequestHandle post(Context context, String url, HttpEntity entity, String contentType,
AsyncHttpResponseHandler responseHandler)
{
return client.post(context, url, entity, contentType, responseHandler);
} public static RequestHandle post(Context context, String url, Header[] headers, RequestParams params,
String contentType, AsyncHttpResponseHandler responseHandler)
{
return client.post(context, url, headers, params, contentType, responseHandler);
} public static RequestHandle post(Context context, String url, Header[] headers, HttpEntity entity,
String contentType, AsyncHttpResponseHandler responseHandler)
{
return client.post(context, url, headers, entity, contentType, responseHandler);
} /**
* calcel the context relative request
* @param context
* @param mayInterruptIfRunning
*/
public void calcelRequests(Context context, boolean mayInterruptIfRunning)
{
client.cancelRequests(context, mayInterruptIfRunning);
} /**
* cancel current all request in app
* @param mayInterruptIfRunning
*/
public void cacelAllrequests(boolean mayInterruptIfRunning)
{
client.cancelAllRequests(mayInterruptIfRunning);
} public static void setHttpContextAttribute(String id, Object obj)
{
client.getHttpContext().setAttribute(id, obj);
} public static Object getHttpContextAttribute(String id)
{
return client.getHttpContext().getAttribute(id);
} public static void removeHttpContextAttribute(String id)
{
client.getHttpContext().removeAttribute(id);
} /**
* set the cookie store
* @param cookieStore
*/
public static void setCookieStore(CookieStore cookieStore)
{
client.setCookieStore(cookieStore);
} /**
* remove the cookie store
*/
public static void removeCookieStore()
{
removeHttpContextAttribute(ClientContext.COOKIE_STORE);
}
}
6.登陆DEMO使用
Cookie的保存,
public class MyApplicaton extends Application {
private static MyApplicaton app;
@Override
public void onCreate() {
super.onCreate();
app = this;
/**
* 为全局 CommonClient加入CookieStore,从PersistentCookieStore中能够拿出全部Cookie
*/
CommonClient.setCookieStore(new PersistentCookieStore(this));
}
public static MyApplicaton getInstance() {
return app;
}
}
响应体的处理:
private void requestLogin()
{
RequestParams params = new RequestParams();
params.put("mb", "");
params.put("pwd", "");
CommonClient.post(this, URL, params, new CommonJsonResponseHandler(
new DisposeDataHandle()
{
@Override
public void onSuccess(Object responseObj)
{
Log.e("------------->", responseObj.toString()); } @Override
public void onFailure(Object reasonObj)
{
Log.e("----->", ((LogicException)reasonObj).getEmsg());
} @Override
public void onProgress(long bytesWritten, long totalSize)
{
Log.e("------------->", bytesWritten + "/" + totalSize);
}
}));
}
经过以上封装后。基于的http功能都具备了,假设开发中遇到一些特殊的功能,可能再依据详细的需求扩展。
android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件的更多相关文章
- Android热门网络框架Volley详解[申明:来源于网络]
Android热门网络框架Volley详解[申明:来源于网络] 地址:http://www.cnblogs.com/caobotao/p/5071658.html
- Android-Volley网络通信框架(二次封装数据请求和图片请求(包含处理请求队列和图片缓存))
1.回想 上篇 使用 Volley 的 JsonObjectRequest 和 ImageLoader 写了 电影列表的样例 2.重点 (1)封装Volley 内部 请求 类(请求队列,数据请求,图片 ...
- 【Android开源项目分析】android轻量级开源缓存框架——ASimpleCache(ACache)源代码分析
转载请注明出处:http://blog.csdn.net/zhoubin1992/article/details/46379055 ASimpleCache框架源代码链接 https://github ...
- Android 基于Socket的聊天应用(二)
很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的 ...
- axios基于常见业务场景的二次封装
axios axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中.在前端框架中的应用也是特别广泛,不管是vue还是react,都有很多项目用axios作为网络 ...
- 基于bootstrap table配置的二次封装
准备 jQuery js css 引用完毕 开始 如果对bootstrap table 的方法与事件不熟悉: Bootstrap table方法,Bootstrap table事件 <table ...
- Vue.js 自定义组件封装实录——基于现有控件的二次封装(以计时器为例)
在本人着手开发一个考试系统的过程中,出现了如下一个需求:制作一个倒计时的控件显示在试卷页面上.本文所记录的就是这样的一个过程. 前期工作 对于这个需求,自然我想到的是有没有现成的组件可以直接使用(本着 ...
- 二次封装这几个 element-ui 组件后,大大减少了我 CRUD 的时间
element-ui 因其组件丰富.可拓展性强.文档详细等优点成为 Vue 最火的第三方 UI 框架.element-ui 其本身就针对后台系统设计了很多实用的组件,基本上满足了平时的开发需求. 既然 ...
- 对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache
虽然jquery的较新的api已经很好用了, 但是在实际工作还是有做二次封装的必要,好处有:1,二次封装后的API更加简洁,更符合个人的使用习惯:2,可以对ajax操作做一些统一处理,比如追加随机数或 ...
随机推荐
- Test-我喜欢LInux
测试发帖流程 哈哈 习惯一下先.
- 紫书 例题 10-6 UVa 1635 (二项式定理+唯一分解定理)
首先可以发现按照题目的算法最后得出来是一个杨辉三角 如果ai的系数是m的倍数,那么i即为答案 因为这个系数可能很大,而我们只需要判断倍数 所以我们就把m分解质因数,然后判断每一个系数 的质因数的幂是不 ...
- 【CS Round #36 (Div. 2 only) A】Bicycle Rental
[题目链接]:https://csacademy.com/contest/round-36/task/bicycle-rental/ [题意] 让你从n辆车中选一辆车; 每一辆车有3个属性 1.到达车 ...
- ActiveMQ学习总结(8)——消息队列设计精要
消息队列已经逐渐成为企业IT系统内部通信的核心手段.它具有低耦合.可靠投递.广播.流量控制.最终一致性等一系列功能,成为异步RPC的主要手段之一. 当今市面上有很多主流的消息中间件,如老牌的Activ ...
- Spring学习总结(12)——Druid连接池及监控在spring配置
Druid连接池及监控在spring配置如下: <bean id="dataSource" class="com.alibaba.druid.pool.DruidD ...
- 洛谷—— P2934 [USACO09JAN]安全出行Safe Travel || COGS ——279|| BZOJ——1576
https://www.luogu.org/problem/show?pid=2934 题目描述 Gremlins have infested the farm. These nasty, ugly ...
- HTML学习----------DAY2第四节
HTML 文档是由 HTML 元素定义的. HTML 元素 HTML 元素指的是从开始标签(start tag)到结束标签(end tag)的所有代码. 注释:开始标签常被称为开放标签(opening ...
- RenderScript on LLVM笔记
Android 为何引入 Render Script: 3D 可移植 ( 直接用 opengl 也能够移植呀?) 性能 易用性 ( 让 opengl 难入门的人,用 Render Script ?) ...
- Linux学习笔记--cp命令(复制)
cp:英文名copy,复制的意思. 1. 命令格式: cp [选项] 源文件或文件夹 目标文件或文件夹 cp [选项] 源文件1 源文件2 源文件3 ... 目标文件夹 2. 经常使用选项: &quo ...
- 轻松掌握Ubuntu Linux的3D桌面快捷键使用
视频下载地址: http://115.com/file/be4n23v6#linux3d.rar 轻松掌握Ubuntu Linux的3D桌面快捷键使用 高级3D桌面展示 本文出自 "李晨光原 ...