网络请求是全部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,二次封装为通用网络请求组件的更多相关文章

  1. Android热门网络框架Volley详解[申明:来源于网络]

    Android热门网络框架Volley详解[申明:来源于网络] 地址:http://www.cnblogs.com/caobotao/p/5071658.html

  2. Android-Volley网络通信框架(二次封装数据请求和图片请求(包含处理请求队列和图片缓存))

    1.回想 上篇 使用 Volley 的 JsonObjectRequest 和 ImageLoader 写了 电影列表的样例 2.重点 (1)封装Volley 内部 请求 类(请求队列,数据请求,图片 ...

  3. 【Android开源项目分析】android轻量级开源缓存框架——ASimpleCache(ACache)源代码分析

    转载请注明出处:http://blog.csdn.net/zhoubin1992/article/details/46379055 ASimpleCache框架源代码链接 https://github ...

  4. Android 基于Socket的聊天应用(二)

    很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的 ...

  5. axios基于常见业务场景的二次封装

    axios axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中.在前端框架中的应用也是特别广泛,不管是vue还是react,都有很多项目用axios作为网络 ...

  6. 基于bootstrap table配置的二次封装

    准备 jQuery js css 引用完毕 开始 如果对bootstrap table 的方法与事件不熟悉: Bootstrap table方法,Bootstrap table事件 <table ...

  7. Vue.js 自定义组件封装实录——基于现有控件的二次封装(以计时器为例)

    在本人着手开发一个考试系统的过程中,出现了如下一个需求:制作一个倒计时的控件显示在试卷页面上.本文所记录的就是这样的一个过程. 前期工作 对于这个需求,自然我想到的是有没有现成的组件可以直接使用(本着 ...

  8. 二次封装这几个 element-ui 组件后,大大减少了我 CRUD 的时间

    element-ui 因其组件丰富.可拓展性强.文档详细等优点成为 Vue 最火的第三方 UI 框架.element-ui 其本身就针对后台系统设计了很多实用的组件,基本上满足了平时的开发需求. 既然 ...

  9. 对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache

    虽然jquery的较新的api已经很好用了, 但是在实际工作还是有做二次封装的必要,好处有:1,二次封装后的API更加简洁,更符合个人的使用习惯:2,可以对ajax操作做一些统一处理,比如追加随机数或 ...

随机推荐

  1. CF817F MEX Queries(线段树上二分)

    题意 维护一个01串,一开始全部都是0 3种操作 1.把一个区间都变为1 2.把一个区间都变为0 3.把一个区间的所有数字翻转过来 每次操作完成之后询问区间最小的0的位置 l,r<=10^18 ...

  2. vSphere VCSA5.5加入AD域环境问题记录

    vSphere VCSA5.5加入AD域环境问题记录 实验目的: 搭建一套vSphere VCSA5.5,并加入新搭建的AD域,并使用一个域用户登录VC,赋予对VC的只读权限. 实验环境: 使用VMW ...

  3. python etree.HTML

    1.编码问题(编码参数 parser): resp_html = etree.HTML(res,parser=etree.HTMLParser(encoding='gbk')) 2.大小写问题(大写转 ...

  4. CSU 1364 Interview RMQ

    题意: 瑶瑶有一家有一家公司,最近他想招m个人.因为他的公司是如此的出名,所以有n个人来参加面试.然而,瑶瑶是如此忙,以至于没有时间来亲自面试他们.所以他准备选择m场面试来测试他们. 瑶瑶决定这样来安 ...

  5. div和css:行内元素和块元素的水平和垂直居中

    行内元素: 水平居中:text-align:center ul水平居中:加 display:table; margin:0 auto; 此元素会作为块级表格来显示(类似 <table>), ...

  6. Java基础学习总结(14)——Java对象的序列化和反序列化

    一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化. 把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种用途: 1) 把对象的字节序列永久地保存到硬盘上,通常存 ...

  7. [React Native] Use the SafeAreaView Component in React Native for iPhone X Compatibility

    In this lesson, you will learn how to use the SafeAreaView component to avoid the sensor cluster (th ...

  8. Android——4.2.2 文件系统文件夹分析

    近期公司要整android内部培训,分配给我写个培训文档.这里记录例如以下: 撰写不易,转载请注明出处:http://blog.csdn.net/jscese/article/details/4089 ...

  9. Ehcache整合spring配置,配置springMVC缓存

    为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO.下面说明一下ehcache和spring整合配置. 1.   需要的jar包 slf4j-api-1.6.1.jar ehcache-c ...

  10. Zuul 2 : The Netflix Journey to Asynchronous, Non-Blocking Systems--转

    原文地址:http://techblog.netflix.com/2016/09/zuul-2-netflix-journey-to-asynchronous.html We recently mad ...