Android Asynchronous Http Client--Android 开源的网络异步加载类

注:本文转自http://blog.csdn.net/qduningning/article/details/34829429

【转载】Android Asynchronous Http Client--Android 开源的网络异步加载类

Android Asynchronous Http Client(AHC)

一个回调式的Android网络请求库

概括:

AHC是基于Apache的HttpClient 库,所有的网络请求过程在UI线程之外进行,而回调是在Handler里面处理。也可以再Service或者后台程序里面使用,这个库会自动识别并在相应的Context进行处理。

特点:

  1. 异步发送HTTP请求,在回调函数中处理响应
  2. HTTP请求过程不在UI线程进行
  3. 使用线程池来管理并发数
  4. 支持GET/POST请求参数单独设置
  5. 无需其他库上传序列化JSON数据
  6. 处理重定向
  7. 体积小,只有90K
  8. 针对不同的网络连接对重试次数进行智能优化
  9. 支持gzip
  10. 二进制通信协议使用BinaryHttpResponseHandler处理
  11. 内置Json解析,使用JsonHttpResponseHandler对响应进行处理
  12. 使用FileAsyncHttpResponseHandler直接将响应保存到文件中
  13. 动态保存Cookie,将Cookie保存到应用的SharedPreferences中
  14. 使用BaseJsonHttpResponseHandler可以搭配Jackson JSON,Gson或者其他的Json反序列化库
  15. 支持SAX解析,使用SaxAsyncHttpResponseHandler
  16. 支持多语言多种编码方式,不只是UTF-8

谁在用

Instagram,Pinterest,Pose。。。。

怎么用

MVN:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <dependency>  
  2.     <groupId>com.loopj.android</groupId>  
  3.     <artifactId>android-async-http</artifactId>  
  4.     <version>1.4.5</version>  
  5. </dependency>  
导包:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.loopj.android.http.*;  
创建一个AsyncHttpClient 对象并发送一个请求:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. client.get("http://www.google.com"new AsyncHttpResponseHandler() {  
  2.   
  3.     @Override  
  4.     public void onStart() {  
  5.         // called before request is started  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onSuccess(int statusCode, Header[] headers, byte[] response) {  
  10.         // called when response HTTP status is "200 OK"  
  11.     }  
  12.   
  13.     @Override  
  14.     public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {  
  15.         // called when response HTTP status is "4XX" (eg. 401, 403, 404)  
  16.     }  
  17.   
  18.     @Override  
  19.     public void onRetry(int retryNo) {  
  20.         // called when request is retried  
  21.     }  
  22. });  

推荐用法:定义一个静态的Http Client

新建一个网络工具类,定义一个全局静态的Http Client。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.loopj.android.http.*;  
  2.   
  3. public class TwitterRestClient {  
  4.   private static final String BASE_URL = "http://api.twitter.com/1/";  
  5.   
  6.   private static AsyncHttpClient client = new AsyncHttpClient();  
  7.   
  8.   public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  
  9.       client.get(getAbsoluteUrl(url), params, responseHandler);  
  10.   }  
  11.   
  12.   public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  
  13.       client.post(getAbsoluteUrl(url), params, responseHandler);  
  14.   }  
  15.   
  16.   private static String getAbsoluteUrl(String relativeUrl) {  
  17.       return BASE_URL + relativeUrl;  
  18.   }  
  19. }  
就很容易的在需要请求网路的地方发送 网络请求:
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);
            }
        });
    }
}

API文档http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html

使用PersistentCookieStore保存Cookie

这个库包含一个 PersistentCookieStore  ,这个类是Apache HttpClient CookieStore 接口的实现,它可以自动将cookies保存到SharedPreferences 。
如果你需要使用cookie保持认证会话,这将是特别重要的,因为即使用户关掉了应用仍然可以登录状态。
首先,创建一个AsyncHttpClient对象:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AsyncHttpClient myClient = new AsyncHttpClient();  

现在将client的Cookie保存到一个PersistentCookieStore,构造方法需要有一个上下文(Activity,Application都可以,通常this就OK了)。
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. PersistentCookieStore myCookieStore = new PersistentCookieStore(this);  
  2. myClient.setCookieStore(myCookieStore);  

所有从server获取到的数据都持续的保存。
如果想自己设定cookie,只需要创建一个新的cookie,并调用addCookie:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. BasicClientCookie newCookie = new BasicClientCookie("cookiesare""awesome");  
  2. newCookie.setVersion(1);  
  3. newCookie.setDomain("mydomain.com");  
  4. newCookie.setPath("/");  
  5. myCookieStore.addCookie(newCookie);  
详情请看  PersistentCookieStore Javadoc  


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

类RequestParams 用来为请求添加请求参数,RequestParams 可以有好几种方法进行创建和设置。
1.创建一个空的RequestParams 然后添加参数:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. RequestParams params = new RequestParams();  
  2. params.put("key""value");  
  3. params.put("more""data");  
2.创建一个带有一对参数的RequestParams 
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. RequestParams params = new RequestParams("single""value");  
3.创建一个带有Map的 RequestParams 
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. HashMap<String, String> paramMap = new HashMap<String, String>();  
  2. paramMap.put("key""value");  
  3. RequestParams params = new RequestParams(paramMap);  
详情请参考: RequestParams Javadoc  

使用RequestParams上传文件


RequestParams 可以支持多媒体文件上传,可以通过以下方式实现:
1.将一个Inputstream添加到将要上传的RequestParams 
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. InputStream myInputStream = blah;  
  2. RequestParams params = new RequestParams();  
  3. params.put("secret_passwords", myInputStream, "passwords.txt");  
2.File方式
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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) {}  
3.byte数组形式
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. byte[] myByteArray = blah;  
  2. RequestParams params = new RequestParams();  
  3. params.put("soundtrack"new ByteArrayInputStream(myByteArray), "she-wolf.mp3");  

详情: RequestParams Javadoc  

使用FileAsyncHttpResponseHandler下载二进制文件

类FileAsyncHttpResponseHandler 可以用来获取二进制文件,如图片,语音等文件:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AsyncHttpClient client = new AsyncHttpClient();  
  2. client.get("http://example.com/file.png"new FileAsyncHttpResponseHandler() {  
  3.     @Override  
  4.     public void onSuccess(int statusCode, Header[] headers, File response) {  
  5.         // Do something with the file `response`  
  6.     }  
  7. });  

详情:   FileAsyncHttpResponseHandler Javadoc  

添加基本的认证凭证

一些请求可能需要类似username/password 的凭证
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AsyncHttpClient client = new AsyncHttpClient();  
  2. client.setBasicAuth("username","password/token");  
  3. client.get("http://example.com");  

当然你也可以定制
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AsyncHttpClient client = new AsyncHttpClient();  
  2. client.setBasicAuth("username","password"new AuthScope("example.com"80, AuthScope.ANY_REALM));  
  3. client.get("http://example.com");  

详情: RequestParams Javadoc



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值