自己封装的android客户端http网络框架
整个框架是基于阿帕奇的httpclient搭建的,框架类图如下,我是用Astah Professional画出来,将项目导入,自动生成所有类关系图,还是挺方便的;
核心类是HttpManager和HttpAsyncTakeManager,前者基于threa实现,后者基于asyncTask实现,封装了get和post请求,只需要实例化,并且调用request方法即可;
- HttpAsyncTaskManager http=new HttpAsyncTaskManager(this);
- String url = "http://www.12306.cn/mormhweb/kyfw/ypcx/";
- http.request(url, new StringTaskHandler() {
- @Override
- public void onNetError() {
- // TODO Auto-generated method stub
- System.out.println("---------neterror---------");
- }
- @Override
- public void onSuccess(String result) {
- // TODO Auto-generated method stub
- System.out.println("#####" + result);
- }
- @Override
- public void onFail() {
- // TODO Auto-generated method stub
- System.out.println("---------onFail---------");
- }
- });
TaskHandler<T>是一个抽象泛型类,有四个子类,StringTaskHandler,InputStreamTaskHandler,JsonObjectHandler,JsonArrayHandler,分别可以处理xml流,字符串,json对象;还可以自定义扩展TaskHandler,实现自己的逻辑
- public abstract class TaskHandler<T> {
- /** network is break */
- public abstract void onNetError();
- /**
- * have a successful response
- *
- * @param result
- */
- public abstract void onSuccess(T result);
- /** if the timeout,server error */
- public abstract void onFail();
- /**
- * parse the InputStream,must be override this
- *
- * @param result
- */
- public abstract T parseResult(InputStream result);
- }
一句代码就搞定,请求,有木有很方便呢,整个项目我已经放在github上面了https://github.com/allen1988/android_http_framework