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操作做一些统一处理,比如追加随机数或 ...
随机推荐
- HDU-1225 Football Score 模拟问题(水题)
题目链接:https://cn.vjudge.net/problem/HDU-1225 水题 代码 #include <algorithm> #include <string> ...
- Python内存分配器(如何产生一个对象的过程)
目录 内存分配器 Python分配器分层 第零层--通用的基础分配器 第一层--低级内存分配器 内存结构 arena pool new arena usable_arenas和unused_arena ...
- 紫书 习题 10-13 UVa 11526(打表找规律+分步枚举)
首先看这道题目,我预感商数肯定是有规律的排列的,于是我打表找一下规律 100 / 1 = 100 100 / 2 = 50 100 / 3 = 33 100 / 4 = 25 100 / 5 = ...
- JS几种遍历方式比较
几种遍历方式比较 for of 循环不仅支持数组.大多数伪数组对象,也支持字符串遍历,此外还支持 Map 和 Set 对象遍历. for in 循环可以遍历字符串.对象.数组,不能遍历 Set/Map ...
- 【Android进阶】Junit单元測试环境搭建以及简单有用
单元測试的目的 首先.Junit单元測试要实现的功能,就是用来測试写好的方法是否可以正确的运行,一般多用于对业务方法的測试. 单元測试的环境配置 1.在AndroidManifest清单文件的Appl ...
- libvirt 部分API 介绍
感谢朋友支持本博客.欢迎共同探讨交流,因为能力和时间有限,错误之处在所难免,欢迎指正! 假设转载,请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...
- android数据储存之存储方式
能够将数据储存在内置或可移动存储,数据库,网络.sharedpreference. android能够使用Content provider来使你的私有数据暴漏给其它应用程序. 一.sharedpref ...
- ztree中依据后台中传过来的node的id,将这个node的复选框置为不可用
var treeObj = $.fn.zTree.getZTreeObj("treeDemo");//树对象 var node = treeObj.getNodeByParam(& ...
- 轻松python专题--文本
基础篇:(取材于零基础学python) 7.1 python中的字符串简单介绍与经常使用函数 7.2 字符串常量 7.3 字符串的一般使用 7.4 改动字符串实例 7.5 文本解析 7.6 字符串格式 ...
- USACO2011 Jan:公司利润
简要题意: 奶牛开了家公司,已经连续运作了N 天.它们在第i 天获得了Ai元的利润,不过有些天是亏钱的,这种情况下利润就是一个负数.约翰想为它们写个新闻,吹嘘它们的惊人业绩.请你帮助他选出一段连续的日 ...