android-async-http框架是一个开源的Android异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果,可以轻松的获取网络数据或者向服务器发送数据,使用起来非常简单。
其主要特征如下:处理异步Http请求,并通过匿名内部类处理回调结果,Http异步请求均位于非UI线程,不会阻塞UI操作,通过线程池处理并发请求处理文件上传、下载,响应结果自动打包JSON格式.自动处理连接断开时请求重连.
项目托管在Github,详细内容请访问:https://github.com/loopj/android-async-http 下载jar包和开发文档等,然后将jar包引入我们自己的项目的libs目录中。
特性:
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)
Multipart file uploads with no additional third party libraries
Streamed JSON uploads with no additional libraries
Handling circular and relative redirects
Tiny size overhead to your application, only 90kb for everything
Automatic smart request retries optimized for spotty mobile connections
Automatic gzip response decoding support for super-fast requests
Binary protocol communication with BinaryHttpResponseHandler
Built-in response parsing into JSON with JsonHttpResponseHandler
Saving response directly into file with FileAsyncHttpResponseHandler
Persistent cookie store, saves cookies into your app’s SharedPreferences
Integration with Jackson JSON, Gson or other JSON (de)serializing libraries with BaseJsonHttpResponseHandler
Support for SAX parser with SaxAsyncHttpResponseHandler
Support for languages and content encodings, not just UTF-8
官方建议使用一个静态的AsyncHttpClient:
public class HttpClientUtils {
private static String sessionId = null;
private static AsyncHttpClient client = new AsyncHttpClient();
private static PersistentCookieStore cookieStore ;
static {
//设置网络超时时间
client.setTimeout(5000);
}
public static void get(String url, AsyncHttpResponseHandler responseHandler) {
client.get(url, responseHandler);
}
public static void get(Context context,String url,ResponseHandlerInterface responseHandler) {
client.get(context, url, responseHandler);
}
public static void get(String url,RequestParams params, ResponseHandlerInterface responseHandler) {
client.get(url, params, responseHandler);
}
public static void get(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) {
client.get(context, url, params, responseHandler);
}
public static void get(Context context, String url, Header[] headers, RequestParams params, ResponseHandlerInterface responseHandler) {
client.get(context, url, headers, params, responseHandler);
}
public static void post(String url,RequestParams params, ResponseHandlerInterface responseHandler){
client.post(url, params, responseHandler);
}
public static AsyncHttpClient getClient(){
return client;
}
public static String getSessionId() {
return sessionId;
}
public static void setSessionId(String sessionId) {
HttpClientUtils.sessionId = sessionId;
}
public static PersistentCookieStore getCookieStore() {
return cookieStore;
}
public static void setCookieStore(PersistentCookieStore cookieStore) {
HttpClientUtils.cookieStore = cookieStore;
client.setCookieStore(cookieStore);
}
}
**
**
AsyncHttpRequest
继承自Runnabler,被submit至线程池执行网络请求并发送start,success等消息
AsyncHttpResponseHandler
接收请求结果,一般重写onSuccess及onFailure接收请求成功或失败的消息,还有onStart,onFinish等消息
TextHttpResponseHandler
继承自AsyncHttpResponseHandler,只是重写了AsyncHttpResponseHandler的onSuccess和onFailure方法,将请求结果由byte数组转换为String
JsonHttpResponseHandler
继承自TextHttpResponseHandler,同样是重写onSuccess和onFailure方法,将请求结果由String转换为JSONObject或JSONArray
BaseJsonHttpResponseHandler
继承自TextHttpResponseHandler,是一个泛型类,提供了parseResponse方法,子类需要提供实现,将请求结果解析成需要的类型,子类可以灵活地使用解析方法,可以直接原始解析,使用gson等。
RequestParams
请求参数,可以添加普通的字符串参数,并可添加File,InputStream上传文件
AsyncHttpClient
核心类,使用HttpClient执行网络请求,提供了get,put,post,delete,head等请求方法,使用起来很简单,只需以url及RequestParams调用相应的方法即可,还可以选择性地传入Context,用于取消Content相关的请求,同时必须提供ResponseHandlerInterface(AsyncHttpResponseHandler继承自ResponseHandlerInterface)的实现类,一般为AsyncHttpResponseHandler的子类,AsyncHttpClient内部有一个线程池,当使用AsyncHttpClient执行网络请求时,最终都会调用sendRequest方法,在这个方法内部将请求参数封装成AsyncHttpRequest(继承自Runnable)交由内部的线程池执行。
SyncHttpClient
继承自AsyncHttpClient,同步执行网络请求,AsyncHttpClient把请求封装成AsyncHttpRequest后提交至线程池,SyncHttpClient把请求封装成AsyncHttpRequest后直接调用它的run方法。
简单的get请求
HttpClientUtils.get("http://www.baidu.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.println(response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable
error)
{
error.printStackTrace(System.out);
}
});
RequestParams params = new RequestParams();
params.put("value1", value1);
params.put("value2", value2);
HttpClientUtils.get(url, params, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
//请求成功回调
}
@Override
public void onFinish() { //请求完成
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
//请求失败
}
});
RequestParams params = new RequestParams();
params.put("value1", value1);
params.put("value2", value2);
HttpClientUtils.get(url, params, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
//请求成功回调
}
@Override
public void onFinish() { //请求完成
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
//请求失败
}
});
今天就先简单介绍android-async-http的基本使用,android-async-http开源框架还有很多方法没有介绍,在稍后的文章再深入讲解,读者也可以自己去探索android-async-http的更多功能。
在此欢迎大家关注我的个人微信公众号AndroidSharer,分享软件开发相关技术包括Android、Java Web、HTML5以及产品研发干货,偶尔喝点鸡汤