在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Instagram和Pinterest的Android版就是用的这个网络请求库。这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。
其主要特征如下:
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
- Tiny size overhead to your application, only 25kb for everything
- Automatic smart request retries optimized for spotty mobile connections
- Automatic gzip response decoding support for super-fast requests
- Binary file (images etc) downloading with
BinaryHttpResponseHandler
- Built-in response parsing into JSON with
JsonHttpResponseHandler
- Persistent cookie store, saves cookies into your app’s SharedPreferences
- 处理异步Http请求,并通过匿名内部类处理回调结果
- GET/POST 请求参数构造器
- Http请求均位于非UI线程,不会阻塞UI操作
- 通过线程池处理并发请求
- 处理文件上传、下载
- 响应结果自动打包JSON格式
- 自动处理连接断开时请求重连
基本用法:
从github上下载最新的jar文件,然后拷贝到Android工程的libs目录下
创建一个AsyncHttpClient实例,然后发送网络请求:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
官方推荐用法:使用一个静态的Http Client
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
// 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;
}
}
一个简单的使用示例:
import org.json.*;
import com.loopj.android.http.*;
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
}
如果需要传递参数可以使用 RequestParams
更多具体用法请参考官网说明文档 http://loopj.com/android-async-http/