天天看点

Android Asynchronous Http Client概述:特征:安装和基本用法:建议使用用法:创建一个静态的Http Client:使用PersistentCookieStore进行Cookie的持久化存储:使用RequestParams添加GET/POST请求参数:使用RequestParams上传文件:使用BinaryHttpResponseHandler下载二进制文件:添加基本的Http证书认证(Auth credentials):

android-async-http大概是Android开发中使用最多的开源网络框架了,今天完整看了下官方文档,顺便记录下来,方便大家使用。

官网: http://loopj.com/android-async-http/ Github: https://github.com/loopj/android-async-http

概述:

一个 在众多 Apache HttpCilent 库中排名靠前的为Android开发的基于异步回调的HttpClient。所有的请求都在你的App的UI线程之外,但是所有的回调逻辑将会在这个CallBack被创建的线程上执行,这与Handler Message处理过程相同。

特征:

1、创建异步的Http请求,在匿名回调中处理返回的相应。 2、Http请求发生在UI线程之外。 3、请求使用线程池(ThreadPool)来解决并发资源使用。 4、GET/POST 参数创建者(RequestParams)。 5、不需要任何附加的第三方库实现 Multipart file 上传 。 6、对你的APP占用空间小,所有东西仅25K 7、尽量为不同的手机实现请求重连接。 8、为高速请求提供自动的gzip响应解码。 9、二进制文件(图片等)下载使用 BinaryHttpResponseHandler。 10、固定的Response解析成JSON使用 JsonHttpResponseHandler 。 11、持久化的Cookie存储,将Cookie保存到APP的SharePreferences中。

安装和基本用法:

1)从Github上下载最新的jar文件并放置在你的APP的lib文件夹下。

2)从Github上下载源文件配置成库工程,让你的Project引用。

导入包: 创建一个AsyncHttpClient对象并创建一个请求。

AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://www.google.com", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response);
        }
    });
           

建议使用用法:创建一个静态的Http Client:

这个例子中,我们将创建一个拥有静态访问方法的Http Client对象,以使我可以方便的与接口进行通讯。

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  和 AsyncHttpResponseHandler的说明文档可以查看更详细的信息。

使用PersistentCookieStore进行Cookie的持久化存储:

这个Library包含了一个实现了Apache HttpClient CookieStore 接口的持久化Cookie类 PersistentCookieStore , PersistentCookieStore 会自动的将Cookies保存到SharePreferences中。 如果你想使用Cookie来管理认证Sessions( authentication sessions ),这将非常有用。用户将会保持登录状态,尽管他关闭并重新打开APP。

首先,创建一个AsyncHttpClient实例:

创建一个 PersistentCookieStore对象(构造方法里的参数为Activity 或 Application Context,一般this就行了)。

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

这样,任何来自服务器的Cookie都将会被持久化存储。

添加你自己的Cookie到持久化存储,简单的创建一个cookie并调用addCookie方法:

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

查看   PersistentCookieStore Javadoc  说明文档获取更多信息。

使用RequestParams添加GET/POST请求参数:

RequestParams类是为GET或POST请求添加额外的参数。 RequestParams类可以通过一下几种构造方法创建:

1)直接创建一个空的RequestParams对象,然后再添加参数

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

2)创建一个只有一个参数的RequestParams对象:

3)通过一个包含key=value 的Map来创建:

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

查看 RequestParams Javadoc文档获取更多信息。

使用RequestParams上传文件:

RequestParams附加支持 multipart file上传:

1)添加一个InputStream到RequestParams上传:

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

2)添加一个File对象到RequestParams上传:

    File  myFile   =   new   File ( "/path/to/file.png" );     RequestParams   params   =   new   RequestParams ();

try {
        params.put("profile_picture", myFile);
    } catch(FileNotFoundException e) {}
           

3)添加一个byte[]到RequestParams上传:

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
        }
    });
           

查看 BinaryHttpResponseHandler Javadoc文档获取更多信息。

添加基本的Http证书认证(Auth credentials):

当与一些使用证书认证的服务接口进行通讯时,以小额请求可能需要 username/password认证。你可以使用 setBasicAuth()来提供你的证书。

默认用法:

AsyncHttpClient client = new AsyncHttpClient();
    client.setBasicAuth("username","password/token");
    client.get("http://example.com");
           

指定host、port、和realm的用法(推荐用法):

AsyncHttpClient client = new AsyncHttpClient();
    client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
    client.get("http://example.com");
           

查看 RequestParams Javadoc文档获取更多信息。