首页 > 代码库 > AsyncHttpClient

AsyncHttpClient

 

AsyncHttpClient来异步网络数据

AsyncHttpClient是异步的,但是有时候我们需要得到请求的结果集来返回给某个函数,由于是异步的,所以不能够直接return会去,所以可以定义一个interface来给调用AsyncHttpClient方法的一个回调来获取结果集。

 

 1 public void click(View view) { 2         AsyncHttpClient client = new AsyncHttpClient(); 3         try { 4             String url = "http://url?name=" 5                     + URLEncoder.encode("aaa", "utf-8") + "&pass=" 6                     + URLEncoder.encode("bbb", "utf-8"); 7             client.get(url, new AsyncHttpResponseHandler() { 8                 @Override 9              public void onSuccess(int statusCode, Header[] headers,10                         byte[] responseBody) {11                     super.onSuccess(statusCode, headers, responseBody);12 13                     Toast.makeText(Main.this,14                             "请求成功" + new String(responseBody), 0).show();15                 }16 17                 @Override18               public void onFailure(int statusCode, Header[] headers,19                         byte[] responseBody, Throwable error) {20                     // TODO Auto-generated method stub21                 super.onFailure(statusCode, headers, responseBody, error);22                 }23             });24         } catch (Exception e) {25         }26 27     }28 29     public void postclick(View view) {30         try {31             AsyncHttpClient client = new AsyncHttpClient();32             String url = "http://url";33             RequestParams params = new RequestParams();34             params.put("name", "张三");35             params.put("pass", "123456");36            client.post(url, params, new AsyncHttpResponseHandler() {37 38                 @Override39                 public void onSuccess(int statusCode, Header[] headers,40                         byte[] responseBody) {41                     super.onSuccess(statusCode, headers, responseBody);42                    Toast.makeText(Main.this,43                            "请求成功" + new String(responseBody), 0).show();44                 }45 46             });47 48         } catch (Exception e) {49             // TODO: handle exception50         }51 52     }53 54     public void btnupfile(View view) {55 56         AsyncHttpClient client = new AsyncHttpClient();57 58         RequestParams params = new RequestParams();59 60         try {61             File file = new File("/sdcard/1.jpg");62             System.out.println(file);63             params.put("pic", file);64 65           client.post("http://url", params,66                   new AsyncHttpResponseHandler() {67                    @Override68                     public void onSuccess(int statusCode, Header[] headers,69                         byte[] responseBody) {70                         super.onSuccess(statusCode, headers, responseBody);71                         Toast.makeText(Main.this,72                                   "上传文件成功!", 0).show();73                         }74                     });75 76         } catch (Exception e) {77             // TODO Auto-generated catch block78             e.printStackTrace();79         }80 81     }

  android-async-http 开源框架可以使我们轻松地获取网络数据或者向服务器发送数据,最关键的是,它是异步框架,在底层使用线程池处理并发请求,效率很高,使用又特别简单。

    以往我们在安卓上做项目,比如要下载很多图片、网页或者其他的资源,多数开发者会选择一个线程一个下载任务这种模型,因为安卓自带的 AndroidHttpClient 或者 java 带的 java.net.URL ,默认都是阻塞式操作。这种模型效率不高,对并发要求高的 APP 来讲,并不适用。有的人会选择使用 nio 自己实现,代码复杂度又很高。

    AsyncHttpClient 作为 android-async-http 框架的一个核心应用类,使用简单,可以处理文本、二进制等各种格式的 web 资源。下面提供一些代码来看如何使用:

 1 public class Downloader { 2     public static AsyncHttpClient mHttpc = new AsyncHttpClient(); 3     public static String TAG = "Downloader"; 4      5     public void downloadText(String uri){ 6         mHttpc.get(uri, null, new AsyncHttpResponseHandler(){ 7             @Override 8             public void onSuccess(String data){ 9             Log.i(TAG, "downloaded, thread id " + Thread.currentThread().getId());10                 // TODO: do something on11             }12             @Override13             public void onFailure(Throwable e, String data){14                 Log.i(TAG, "download failed.");15                 // TODO: error proceed16             }17         });18     }19     20     public void downloadImage(String uri, String savePath){21         mHttpc.get(uri, new ImageResponseHandler(savePath));22     }23     24     public class ImageResponseHandler extends BinaryHttpResponseHandler{25         private String mSavePath;26         27         public ImageResponseHandler(String savePath){28             super();29             mSavePath = savePath;30         }31         @Override32         public void onSuccess(byte[] data){33             Log.i(TAG, "download image, file length " + data.length);34             // TODO: save image , do something on image35         }36         @Override37         public void onFailure(Throwable e, String data){38             Log.i(TAG, "download failed");39             // TODO : error proceed40         }41     }42 };

 

AsyncHttpClient