asynchttpclient学习

来源:互联网 发布:java格式化json字符串 编辑:程序博客网 时间:2024/06/06 03:28


官方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 依赖

基础使用

  1. AsyncHttpClient client = new AsyncHttpClient();
  2. client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {
  3. @Override
  4. public void onStart() {
  5. // called before request is started
  6. }
  7. @Override
  8. public void onSuccess(int statusCode, Header[] headers, byte[] response) {
  9. // called when response HTTP status is "200 OK"
  10. }
  11. @Override
  12. public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
  13. // called when response HTTP status is "4XX" (eg. 401, 403, 404)
  14. }
  15. @Override
  16. public void onRetry(int retryNo) {
  17. // called when request is retried
  18. }

});

这里返回的是原生的字节流,你也可以使用其他的ResponseHandler自动转化为响应的格式,已经提供的ResponseHandler

  • AsyncHttpResponseHandler
  • BaseJsonHttpResponseHandler
  • BinaryHttpResponseHandler
  • BlackholeHttpResponseHandler
  • DataAsyncHttpResponseHandler
  • FileAsyncHttpResponseHandler
  • JsonHttpResponseHandler
  • RangeFileAsyncHttpResponseHandler
  • SaxAsyncHttpResponseHandler
  • TextHttpResponseHandler

推荐用法:使用静态Http Client

  1. import com.loopj.android.http.*;
  2. public class TwitterRestClient {
  3. private static final String BASE_URL = "https://api.twitter.com/1/";
  4. private static AsyncHttpClient client = new AsyncHttpClient();
  5. public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
  6. client.get(getAbsoluteUrl(url), params, responseHandler);
  7. }
  8. public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
  9. client.post(getAbsoluteUrl(url), params, responseHandler);
  10. }
  11. private static String getAbsoluteUrl(String relativeUrl) {
  12. return BASE_URL + relativeUrl;
  13. }
  14. }

在代码中需要http请求时:

  1. import org.json.*;
  2. import com.loopj.android.http.*;
  3. class TwitterRestClientUsage {
  4. public void getPublicTimeline() throws JSONException {
  5. TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
  6. @Override
  7. public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
  8. // If the response is JSONObject instead of expected JSONArray
  9. }
  10. @Override
  11. public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
  12. // Pull out the first event on the public timeline
  13. JSONObject firstEvent = timeline.get(0);
  14. String tweetText = firstEvent.getString("text");
  15. // Do something with the response
  16. System.out.println(tweetText);
  17. }
  18. });
  19. }
  20. }

使用Cookie

这是非常有用的,如果你想使用Cookie管理认证sessions,用户将保持登录后,即使关闭和重新打开应用程序。

首先创建一个AsyncHttpClient

  1. AsyncHttpClient myClient = new AsyncHttpClient();

new 一个PersistentCookieStore

  1. PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
  2. myClient.setCookieStore(myCookieStore);

从服务器接收到的任何Cookie现在将存储在持久性的CookieStore中。 
添加cookie:

  1. BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
  2. newCookie.setVersion(1);
  3. newCookie.setDomain("mydomain.com");
  4. newCookie.setPath("/");
  5. myCookieStore.addCookie(newCookie);

添加请求参数 RequestParams

  1. RequestParams params = new RequestParams();
  2. params.put("key", "value");
  3. params.put("more", "data");

当只有一个参数是可以这么写:

  1. RequestParams params = new RequestParams("single", "value");

或者也可以使用过Map键值对给RequestParams添加参数

  1. HashMap<String, String> paramMap = new
  2. HashMap<String, String>();
  3. paramMap.put("key", "value");
  4. RequestParams params = new RequestParams(paramMap);

使用RequestParams上传文件

给RequestParams添加InputStream

  1. InputStream myInputStream = blah;
  2. RequestParams params = new RequestParams();
  3. params.put("secret_passwords", myInputStream, "passwords.txt");

给RequestParams添加File

  1. File myFile = new File("/path/to/file.png");
  2. RequestParams params = new RequestParams();
  3. try {
  4. params.put("profile_picture", myFile);
  5. } catch(FileNotFoundException e) {}

给RequestParams添加字节数组

  1. byte[] myByteArray = blah;
  2. RequestParams params = new RequestParams();
  3. params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

用FileAsyncHttpResponseHandler下载二进制文件

  1. AsyncHttpClient client = new AsyncHttpClient();
  2. client.get("https://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
  3. @Override
  4. public void onSuccess(int statusCode, Header[] headers, File response) {
  5. // Do something with the file `response`
  6. }
  7. });

参考文章

http://brightenma.leanote.com/post/android-async-http-AsyncHttpClient-bi


原创粉丝点击