官方github地址:https://github.com/loopj/android-async-http
官方文档:https://loopj.com/android-async-http/
个人理解:之前在一个电商项目中用到Android-async-http,使用起来很方便get post请求,文件图片上传等没有出现什么问题,而且速度也很快而且容易上手。但随着google不支持httpclient请求以及volley 和retrofit与okhttp组合的兴起,老框架Android-async-http渐渐使用比较少,但是仍然值得去学习,在平时的小项目中用Android-async-http也是一个不错的选择
之前在一个项目中用到
android-async-http AsyncHttpClient使用说明:
特点
-
发送异步http请求,在匿名callback对象中处理response;
-
Http请求发生在UI线程之外;
-
内部采用线程池来处理并发请求;
-
GET/POST 参数构造,通过RequestParams类。
-
内置多部分文件上传,不需要第三方库支持;
-
库很小,只有90kb;
-
自动智能的请求重试机制在各种各样的移动连接环境中;
-
自动的gzip响应解码;
-
内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将response写到文件中;
-
永久的cookie保存,内部实现用的是Android的SharedPreferences;
-
通过BaseJsonHttpResponseHandler和各种json库集成;
-
支持SAX解析器;
-
支持各种语言和content编码,不仅仅是UTF-8。
- 持久化cookie到SharedPreferences,可以很方便的完成验证等
添加Gradle 依赖
基础使用
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.baidu.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
}
});
这里返回的是原生的字节流,你也可以使用其他的ResponseHandler自动转化为响应的格式,已经提供的ResponseHandler
- AsyncHttpResponseHandler
- BaseJsonHttpResponseHandler
- BinaryHttpResponseHandler
- BlackholeHttpResponseHandler
- DataAsyncHttpResponseHandler
- FileAsyncHttpResponseHandler
- JsonHttpResponseHandler
- RangeFileAsyncHttpResponseHandler
- SaxAsyncHttpResponseHandler
- TextHttpResponseHandler
推荐用法:使用静态Http Client
import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "https://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;
}
}
在代码中需要http请求时:
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);
}
});
}
}
使用Cookie
这是非常有用的,如果你想使用Cookie管理认证sessions,用户将保持登录后,即使关闭和重新打开应用程序。
首先创建一个AsyncHttpClient
AsyncHttpClient myClient = new AsyncHttpClient();
new 一个PersistentCookieStore
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
从服务器接收到的任何Cookie现在将存储在持久性的CookieStore中。
添加cookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
添加请求参数 RequestParams
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
当只有一个参数是可以这么写:
RequestParams params = new RequestParams("single", "value");
或者也可以使用过Map键值对给RequestParams添加参数
HashMap<String, String> paramMap = new
HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
使用RequestParams上传文件
给RequestParams添加InputStream
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
给RequestParams添加File
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
给RequestParams添加字节数组
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
用FileAsyncHttpResponseHandler下载二进制文件
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
@Override
public void onSuccess(int statusCode, Header[] headers, File response) {
// Do something with the file `response`
}
});
参考文章
http://brightenma.leanote.com/post/android-async-http-AsyncHttpClient-bi