android-async-http AsyncHttpClient介绍和使用

  • Post author:
  • Post category:其他



转自http://www.cnblogs.com/xiaoweiz/p/3916790.html


及http://blog.csdn.net/redarmy_chen/article/details/26976463


android-async-http 是针对Android开发中发送http请求的第三方开源库。


在Android开发中,发送、处理http请求简直太常见了,以至于我们的代码里到处充斥着各种HttpClient和与之相关又臭又长的代码,


它们存在于你代码的各个角落,每次看见都令人作呕,而你仅仅是为了server能返回一个string或者json给你。每次当我自己写这样


的代码时,我都会想能不能简化下这个流程,可能2、3行代码就能搞定。因为针对最简单的case,我只需要提供request url,成功时的


callback和(或)失败时的callback,仅此而已。针对这一类问题(需求),可以说android-async-http提供了几乎完美的解决方案。


通过使用它可以大大简化你的代码,不仅如此,你的代码看上去也优雅多了。


当我第一眼看到它时就被吸引住了,特别是async关键字,干我们这行的都知道,这是异步执行,也就是说它的网络请求自动在非UI


线程里执行,你不需要任何额外的操作(比如手动new一个Thread之类)。项目的官方网站:



http://loopj.com/android-async-http/,

对应的github地址:

https://github.com/loopj/android-async-http


我这里简要介绍下:它是专门针对Android在Apache的

HttpClient

基础上构建的异步的callback-based http client。所有的请求


全在UI线程之外发生,而callback发生在创建它的线程中,应用了Android的Handler发送消息机制。你也可以把AsyncHttpClient应用在


Service中或者后台线程中,库代码会自动识别出它所运行的context。它的feature包括:


1. 发送异步http请求,在匿名callback对象中处理response;


2. http请求发生在UI线程之外;


3. 内部采用线程池来处理并发请求;


4. GET/POST 参数构造,通过RequestParams类。


5. 内置多部分文件上传,不需要第三方库支持;


6. 流式Json上传,不需要额外的库;


7. 能处理环行和相对重定向;


8. 和你的app大小相比来说,库的size很小,所有的一切只有90kb;


9. 自动智能的请求重试机制在各种各样的移动连接环境中;


10. 自动的gzip响应解码;


11. 内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将response写到文件中;


12. 永久的cookie保存,内部实现用的是Android的SharedPreferences;


13. 通过

BaseJsonHttpResponseHandler和

各种json库集成;


14. 支持SAX解析器;


15. 支持各种语言和content编码,不仅仅是UTF-8。


大概翻译了下,这些只是大体的概览,具体的细节还得在使用过程中慢慢感受、学习。


接下来,带领大家看看应用android-async-http来写代码是个啥样子。简单来说你只需要3步,


1. 创建一个AsyncHttpClient;


2. (可选的)通过RequestParams对象设置请求参数;


3. 调用AsyncHttpClient的某个get方法,传递你需要的(成功和失败时)callback接口实现,一般都是匿名内部类


,实现了AsyncHttpResponseHandler,类库自己也提供了好些现成的response handler,你一般不需要自己创建一个。


2.


Installation & Basic Usage

(

安装和基本用法)


Download the latest .jar file from github and place it in your Android app’s


libs/


folder.



从github上下载最新的最新的jar文件.并将其放置在你的Android应用程序的libs /文件夹.


2.1下载方式:


1.从

http://loopj.com/android-async-http/

的页面下载





点击DownLoad即可下载最新的jar文件



2.从

https://github.com/loopj/android-async-http

的页面下载








找到DownLoad ZIP进行下载文件,解压后的目录如下








examples:里面有简单的例子



library:里面存放的是android-async-http开源项目的源码(方法一:可以把library\src\main\java文件下面的文件拷贝到,你应用的src下也可以直接使用)



releases:里面存放的是各个版本的jar文件,(方法二:只需把最新的jar文件拷贝到你应用的libs目录下即可.)



samples:里面存放的也是例子(可供参考)



备注:方法一和方法二只能采用其中之一,建议采用方法二



2.2使用方法






Import the http package.




import com.loopj.android.http.*;

Create a new

AsyncHttpClient

instance and make a request:

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



Adding GET/POST Parameters with

RequestParams


The

RequestParams

class is used to add optional GET or POST parameters to your requests.

RequestParams

can be built and constructed in various ways:

Create empty

RequestParams

and immediately add some parameters:

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

Create

RequestParams

for a single parameter:

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

Create

RequestParams

from an existing

Map

of key/value strings:

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

See the

RequestParams Javadoc

for more information.

Add an

InputStream

to the

RequestParams

to upload:

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

Add a

File

object to the

RequestParams

to upload:

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

Add a byte array to the

RequestParams

to upload:

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

See the

RequestParams Javadoc

for more information.



Downloading Binary Data with

BinaryHttpResponseHandler


The

BinaryHttpResponseHandler

class can be used to fetch binary data such as images and other files. For example:

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