摘要
如果你搞定了前面介绍的CallBack函数与异步,那么现在向你推荐一款十分流行的http异步框架.
基本知识入门
AsyncHttpClient背景
在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Instagram和Pinterest的Android版就是用的这个网络请求库。这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。
特性
处理异步Http请求,并通过匿名内部类处理回调结果
Http请求均位于非UI线程,不会阻塞UI操作
通过线程池处理并发请求
处理文件上传、下载 post / get
响应结果自动打包JSON格式
自动处理连接断开时请求重连
必须掌握核心类
AsyncHttpClient 核心类内部封装了 http与Thread+Handler
AsyncHttpResponseHandler响应处理类 包含很多回调函数{条件成熟时会被调用的函数}
public class RequestParams { //封装了参数处理 例如:K-V 可以暂时 Map)
其他处理类
public class AsyncHttpResponseHandler { //请求返回处理 成功 失败 开始 完成 等自定义的消息
public class BinaryHttpResponseHandler extends AsyncHttpResponseHandler { //字节流返回处理 该库用于处理图片等
public class JsonHttpResponseHandler extends AsyncHttpResponseHandler { //json请求返回处理 服务器与客户端用json交流时使用
常见项目使用相关业务 [必须掌握]
1.1. Get
String url = "http://192.168.10.100:8080/web/";
// 创建客户端类
AsyncHttpClient client = new AsyncHttpClient();
// get请求 非阻塞/异步
client.get(url, // 路径
new AsyncHttpResponseHandler() {
//回调函数:条件:请求失败的情况下
@Override
public void onFailure(int resCode, Header[] header, byte[] result, Throwable e) {
super.onFailure(resCode, header, result, e);
resultText.setText("请求失败");
}
//回调函数:条件:请求成功的情况下 200 主线程:可以直接操作控件
@Override
public void onSuccess(int resCode, Header[] header, byte[] result) {
super.onSuccess(resCode, header, result);
try {
String res=new String(result,"UTF-8");
resultText.setText(res);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// 响应处理类
);
1.2. Post
// 创建客户端类
AsyncHttpClient client = new AsyncHttpClient();
// 创建表单
RequestParams params = new RequestParams();
params.put("username", userName);
params.put("password", password);
// post请求 非阻塞/异步
client.post(url, // 路径
params,// 表单
new AsyncHttpResponseHandler() {
//注意回调函数处理
}}
);
1.3. 文件上传
// 创建客户端类
AsyncHttpClient client = new AsyncHttpClient();
// 创建表单
RequestParams params = new RequestParams();
params.put("filename", "文件名");
params.put("filedes", "文件描述");
try {
params.put("formfile", new File(filePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
// post请求 非阻塞/异步