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操作做一些统一处理,比如追加随机数或 ...
随机推荐
- BZOJ 2141 排队(分块+树状数组)
题意 第一行为一个正整数n,表示小朋友的数量:第二行包含n个由空格分隔的正整数h1,h2,…,hn,依次表示初始队列中小朋友的身高:第三行为一个正整数m,表示交换操作的次数:以下m行每行包含两个正整数 ...
- 前端之CSS属性相关
宽和高 width属性可以为元素设置宽度. height属性可以为元素设置高度. 块级标签才能设置宽度,内联标签的宽度由内容来决定. 字体属性 文字字体 font-family可以把多个字体名称作为一 ...
- MySQL好弱智的一个错误
在sql中执行select是可以查询 但是在linux命令行下执行就报错 ERROR 1059 (42000): Identifier name 'use db_goforit_stati;selec ...
- vue使用,问题
参考链接:https://cn.vuejs.org/v2/guide/index.html *)[Vue warn]: Error in v-on handler: "TypeError: ...
- Python组织文件 实践:查找大文件、 用Mb、kb显示文件尺寸 、计算程序运行时间
这个小程序很简单原本没有记录下来的必要,但在编写过程中又让我学到了一些新的知识,并且遇到了一些不能解决的问题,然后,然后就很有必要记录一下. 这个程序的关键是获取文件大小,本来用 os.path.ge ...
- Linux软防火墙ACL匹配的优化点
首先.请求不要再诬陷Netfilter.尽管它有一些固有性能损耗,但敬请不要将iptables和Netfilter等同,假设你要抓元凶,请直接说iptables,而不要说成Netfilter! ...
- FIFO的设计与仿真
本设计参照齐威王大哥的设计,采用模块化的设计方法,每个模块简单易懂,并进行了每个模块的仿真.最后进行顶层设计,编写了测试激励在modisim上仿真正确, 下面给出代码和测试激励,附上一篇比较好的英文文 ...
- 方便查看线程状况的jsp页面
此方法来自深入理解java虚拟机一书,用作管理员页面,可以随时用浏览器查看线程堆栈 <%@ page language="java" import="java.ut ...
- Android CardView卡片布局 标签: 控件
CardView介绍 CardView是Android 5.0系统引入的控件,相当于FragmentLayout布局控件然后添加圆角及阴影的效果:CardView被包装为一种布局,并且经常在ListV ...
- SQL server无法启动服务,提示“错误1069: 由于登录失败而无法启动服务”
原因:大部分情况是你修改了服务器系统的登录密码,而导致SQL服务无法启动. 解决方法:将sql server(mssql server)服务的登录密码改为系统登录密码或本地登录,如下操作步骤: 在wi ...