官网地址: http://loopj.com/android-async-http/
源码地址:https://github.com/loopj/android-async-http
Features
- Make asynchronous HTTP requests, handle responses in anonymous callbacks 异步请求,回调处理响应
- HTTP requests happen outside the UI thread 请求在子线程中
- Requests use a threadpool to cap concurrent resource usage 使用线程池管理请求(线程)
- GET/POST params builder (RequestParams) 使用RequestParams来设置请求参数
- Multipart file uploads with no additional third party libraries 文件上传不使用第三方类库
- Tiny size overhead to your application, only 60kb for everything 包大小只有60K
- Automatic smart request retries optimized for spotty mobile connections 请求的重连功能
- Automatic gzip response decoding support for super-fast requests 支持gzip
- Optional built-in response parsing into JSON (JsonHttpResponseHandler) 可以使用JsonHttpResponseHandler将响应转化为JSON 类型
- Optional persistent cookie store, saves cookies into your app's SharedPreferences 持久化数据,将Cookie数据保存在SharedPreferences中
常用方式:
封装类:
// Static wrapper library around AsyncHttpClient
public class TwitterRestClient {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
调用类:
class TwitterRestClientUsage {
public void getPublicTimeline() {
TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray timeline) {
try {
JSONObject firstEvent = (JSONObject) timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
需要注意的是,在传递ArrayList时,需要如下传递:
ArrayList<String> mobiles, RequestParams params = new RequestParams();
if (mobiles != null && mobiles.size() > 0) {
for (int i = 0; i < mobiles.size(); i++) {
params.put("mobiles[" + i + "]", mobiles.get(i));
}
}
源码分析:
AsyncHttpRequest.java 文件封装请求
AbstractHttpClient client;
HttpUriRequest request;
HttpContext context;
HttpResponse response = client.execute(request, context);
在构造 AsyncHttpRequest类型对象时,需要传入ResponseHandlerInterface 类型参数,这个是接口类,用于将请求的各种状态通过它传递出去,
AsyncHttpResponseHandler继承自它,TextHttpResponseHandler继承自AsyncHttpResponseHandler,常用的JsonHttpResponseHandler继承自TextHttpResponseHandler,在这些类中对返回值进行解析处理,调用onStart,onFinish,onSuccess,onFailure等方法,我们可以重写这些方法实现回调。
取消请求
调用 HttpUriRequest request ; request.abort();方法。
需要注意的是,取消请求,只能取消那些传入了Context上下文环境的请求。
在请求时,会根据Context,将请求以键值对的形式存在HashMap中,所以取消时,会查找Context,取消对应的请求。