原文: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,RequestParamsandAsyncHttpResponseHandler的文档获取更多的信息

持续的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

更多相关文章

  1. Android(安卓)官方架构组件(三)——ViewModel
  2. ( 经典 ) Android深入浅出之Binder机制
  3. Android:overridePendingTransition()函数介绍
  4. Android倒计时功能的实现(CountDownTimer)
  5. android中跨进程通讯的4种方式
  6. 属性动画和补间动画
  7. Android(安卓)解析gbk、gb2312编码的xml文件(转)
  8. Android(安卓)Volley完全解析(一),初识Volley的基本用法
  9. Java笔记:[反射篇] 利用反射,获取类中的私有内部类对象,并调用该对

随机推荐

  1. PDO预处理与会话控制
  2. vue_1
  3. 意派Epub360丨中秋节合成海报H5案例赏析,
  4. 定义网站相关路由内容
  5. 豆瓣" 饭圈 " 整治,如何采集分析评论
  6. adminlte框架后台模板分块
  7. PHP header 的7种用法
  8. Java Agent 动态修改字节码详情
  9. PyTorch一小时掌握之基本操作篇
  10. 婚恋网站相关控制器和路由