原文:http://loopj.com/android-async-http/
简介
一个异步的基于回调的httpclient的包,所有的请求都不在app的主线程,
但是回调的逻辑会在相同线程执行,作为android的handler的信息来创建回调。
特性
异步http 请求,处理响应在你匿名的回调中。
HTTP 请求在UI线程外
请求使用线程池,并行使用资源
GET/POST 参数构造(RequestParams)
多文件下载不增加第三方库
小空间占用,只有25k
自动重连选项对应移动连接
自动 gzip响应转码支持
二进制(图片)下载使用 BinaryHttpResponseHandler
内置响应解析,通过json使用JsonHttpResponseHandler
连续的cookie存储,保存cooke到你的app的 SharedPreferences
哪些app和开发者在使用
Instagram Pinterest Frontline-Commando Heyzap Pose
安装和使用
下载 .jar 文件from github,放到你app的lib/ 目录
包含http 包
import com.loopj.android.http.*;
创建一个AsyncHttpClient 实例,然后发出一个请求:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { System.out.println(response); } });
推荐使用的方法:创建一个静态的httpclient
在这个例子里,我们会创建一个httpclent类,静态访问让它更容易的通过twitter的api来报纸通讯。
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(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借口实现的类,自动保存cookie到SharedPreferences
这个在你想使用cookie来管理授权session非常游泳,从永辉站点登录后,到关闭或者重新打开你的app
第一步,创建一个AsyncHttpClient 实例:
AsyncHttpClient myClient = new AsyncHttpClient();
现在要设置client的cookie存储到一个新的PersistentCookieStore 实例上,由一个activity或者application context 来构造
PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore);
任何cookie一被接受,就会被持续的cookie存储
天街额外自己的cookie来存储,简单的构造一个新的cookie和调用addCookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome"); newCookie.setVersion(1); newCookie.setDomain("mydomain.com"); newCookie.setPath("/"); myCookieStore.addCookie(newCookie);
更多的看 PersistentCookieStoreJavadoc
使用RequestParam 添加GET/POST 参数
RequestParams 对象使用添加GET和POST参数到请求RequestParams 可以用多种方法构造:
创建一个空RequestParams 然后立即添加很多参数
RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data");
用单个参数创建RequestParams
RequestParams params = new RequestParams("single", "value");
使用已存在的key和value来创建RequestParams
HashMap<String, String> paramMap = new HashMap<String, String>(); paramMap.put("key", "value"); RequestParams params = new RequestParams(paramMap);
看RequestParams Javadoc 获取更多的信息
通过RequestParams上传文件
RequestParams对象额外支持多文件上传
添加InputStream 到RequestParams来上传:
InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt");
添加一个文件对象到RequestParams 来上传:
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");
更多信息看: RequestParams Javadoc
使用BinaryHttpResponseHandler下载二进制的数据
BinaryHttpResponseHandler对象能用于抓取二进制,像图片和文件。例如:
AsyncHttpClient client = new AsyncHttpClient(); String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" }; client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) { @Override public void onSuccess(byte[] fileData) { // Do something with the file } });
更多信息看 BinaryHttpResponseHandlerJavadoc