简介
基于Apache的HttpClient 的一个android异步包.
回调逻辑执行的线程 == 创建Callback的线程(不是创建Httpclient的线程)
举例:
new Thread(new Runnable() { @Override public void run() { Log.d(LOG_TAG, "Before Request"); client.get(Activity.this, URL, headers, null, responseHandler); Log.d(LOG_TAG, "After Request"); } }).start(); //在callback的时候,就要用runOnUiThread
特点:
1.异步请求,匿名回调处理响应
2.http请求在UI线程之外
3.请求试用线程池,共用资源
4.GET/POST 参数构建(RequestParams)
5.多文件上传,并且不需要多余3方库
6.JSON流上传
7.处理循环和定向跳转
8.包只有90k
9.自动重连,根据不同的网络连接方式
10.2进制通讯协议BinaryHttpResponseHandler
11.内置JSON解析JsonHttpResponseHandler
12.文件保存FileAsyncHttpResponseHandler
13。持续cookie存储,保存在SharedPreferences里
14支持多个Json解析,包括GSON,使用BaseJsonHttpResponseHandler
15.支持SAX解析SaxAsyncHttpResponseHandler
16.支持多语言,不止UTF8
top榜上的应用
。。。
安装和使用
安装
compile 'com.loopj.android:android-async-http:1.4.5'
包含
import com.loopj.android.http.*;
创建一个异步的请求
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is "200 OK" } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried } });
最佳实践:创建静态的Http client
创建静态的一个Httpclient类
import com.loopj.android.http.*; 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(int statusCode, Header[] headers, JSONObject response) { // If the response is JSONObject instead of expected JSONArray } @Override public void onSuccess(int statusCode, Header[] headers, 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); } }); } }
更多的可以看文档: AsyncHttpClient, RequestParams and AsyncHttpResponseHandler
持续的Cookie的存储 PersistentCookieStore
库中包含PersistentCookieStore是实现了Apache的HttpClient的CookieStore接口,会自动持续存储
下面是一个例子:
AsyncHttpClient myClient = new AsyncHttpClient(); //设置要存储的Cookie对象 PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore); //等收到响应的时候,对象会自动存储起来。 //还可以自己添加cookie
更多的看 PersistentCookieStore Javadoc
添加 参数
RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); //方法二 RequestParams params = new RequestParams("single", "value"); //方法三 HashMap<String, String> paramMap = new HashMap<String, String>(); paramMap.put("key", "value"); RequestParams params = new RequestParams(paramMap);
See the RequestParams Javadoc for more information.
上传文件(RequestParams)
可进行多文件上传
//以流的形式 InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt"); //以File文件 File myFile = new File("/path/to/file.png"); RequestParams params = new RequestParams(); try { params.put("profile_picture", myFile); } catch(FileNotFoundException e) {} //以byte[] byte[] myByteArray = blah; RequestParams params = new RequestParams(); params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
See the RequestParams Javadoc for more information.
下载二进制文件(FileAsyncHttpResponseHandler)
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, File response) { // Do something with the file `response` } });
See the FileAsyncHttpResponseHandler Javadoc for more information.
添加http基本授权认证
很多请求要带有 用户名/密码 授权。
AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password/token"); client.get("http://example.com"); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM)); client.get("http://example.com");
See the RequestParams Javadoc for more information.
结束