android-async-http仓库:git clone https://github.com/loopj/android-async-http html
android-async-http主页:http://loopj.com/android-async-http/ java
开始使用分析前仍是先了解下Android的HTTP一些过往趣事: android
关于Android HTTP推荐的Google官方连接 git
HttpClient拥有众多的API,实现稳定,bug不多。 HttpURLConnection是一种多用途、轻量的HTTP客户端,使用它来进行HTTP操做能够适用于大多数的应用程序。 HttpURLConnection的API比较简单、扩展容易。不过在Android 2.2版本以前,HttpURLConnection一直存在着一些bug。 好比说对一个可读的InputStream调用close()方法时,就有可能会致使链接池失效了。 因此说2.2以前推荐使用HttpClient,2.2以后推荐HttpURLConnection。 github
好了,那如今话又说回来,在android-async-http中使用的是HttpClient。哎…好像在Volley中分析过Volley对不一样版本进行了判断, 因此针对不一样版本分别使用了HttpClient和HttpURLConnection。仍是google牛逼啊! json
回过神继续android-async-http吧,不瞎扯了。 api
android-async-http是专门针对Android在Apache的HttpClient基础上构建的异步http链接。全部的请求全在UI(主)线程以外执行, 而callback使用了Android的Handler发送消息机制在建立它的线程中执行。 服务器
相似Volley同样,使用一个优秀框架以前就是必须得先知道他的特性,以下就是android-async-http的特性: cookie
android-async-http最简单基础的使用只需以下步骤: 并发
AsyncHttpClient类一般用在android应用程序中建立异步GET, POST, PUT和DELETE HTTP请求, 请求参数经过RequestParams实例建立,响应经过重写匿名内部类ResponseHandlerInterface方法处理。
以下代码展现了使用AsyncHttpClient与AsyncHttpResponseHandler的基础操做:
AsyncHttpClient client = new AsyncHttpClient(); client.get("www.baidu.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onStart() { super.onStart(); } @Override public void onFinish() { super.onFinish(); } @Override public void onRetry(int retryNo) { super.onRetry(retryNo); } @Override public void onCancel() { super.onCancel(); } @Override public void onProgress(int bytesWritten, int totalSize) { super.onProgress(bytesWritten, totalSize); } });
注意:官方推荐使用一个静态的AsyncHttpClient,官方示例代码以下:
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; } }
经过官方这个推荐例子能够发现,咱们在用时能够直接经过类名调用须要的请求方法。因此咱们能够本身多封装一些不一样的请求方法,好比参数不一样的方法,下载方法, 上传方法等。
RequestParams params = new RequestParams(); params.put("username", "yanbober"); params.put("password", "123456"); params.put("email", "yanbobersky@email.com"); /* * Upload a File */ params.put("file_pic", new File("test.jpg")); params.put("file_inputStream", inputStream); params.put("file_bytes", new ByteArrayInputStream(bytes)); /* * url params: "user[first_name]=jesse&user[last_name]=yan" */ Map<String, String> map = new HashMap<String, String>(); map.put("first_name", "jesse"); map.put("last_name", "yan"); params.put("user", map); /* * url params: "what=haha&like=wowo" */ Set<String> set = new HashSet<String>(); set.add("haha"); set.add("wowo"); params.put("what", set); /* * url params: "languages[]=Java&languages[]=C" */ List<String> list = new ArrayList<String>(); list.add("Java"); list.add("C"); params.put("languages", list); /* * url params: "colors[]=blue&colors[]=yellow" */ String[] colors = { "blue", "yellow" }; params.put("colors", colors); /* * url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female" */ List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>(); Map<String, String> user1 = new HashMap<String, String>(); user1.put("age", "30"); user1.put("gender", "male"); Map<String, String> user2 = new HashMap<String, String>(); user2.put("age", "25"); user2.put("gender", "female"); listOfMaps.add(user1); listOfMaps.add(user2); params.put("users", listOfMaps); /* * 使用实例 */ AsyncHttpClient client = new AsyncHttpClient(); client.post("http://localhost:8080/androidtest/", params, responseHandler);
try { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "ryantang"); StringEntity stringEntity = new StringEntity(jsonObject.toString()); client.post(mContext, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){ @Override public void onSuccess(JSONObject jsonObject) { super.onSuccess(jsonObject); } }); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
client.get("http://download/file/test.java", new BinaryHttpResponseHandler() { @Override public void onSuccess(byte[] arg0) { super.onSuccess(arg0); File file = Environment.getExternalStorageDirectory(); File file2 = new File(file, "down"); file2.mkdir(); file2 = new File(file2, "down_file.jpg"); try { FileOutputStream oStream = new FileOutputStream(file2); oStream.write(arg0); oStream.flush(); oStream.close(); } catch (Exception e) { e.printStackTrace(); Log.i(null, e.toString()); } } });
File myFile = new File("/sdcard/test.java"); RequestParams params = new RequestParams(); try { params.put("filename", myFile); AsyncHttpClient client = new AsyncHttpClient(); client.post("http://update/server/location/", params, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, String content) { super.onSuccess(statusCode, content); } }); } catch(FileNotFoundException e) { e.printStackTrace(); }
官方文档里说PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口, 可自动将cookie保存到Android设备的SharedPreferences中, 若是你打算使用cookie来管理验证会话,这个很是有用,由于用户能够保持登陆状态,无论关闭仍是从新打开你的app。
文档里介绍了持久化Cookie的步骤:
下面这个例子就是铁证:
AsyncHttpClient client = new AsyncHttpClient(); PersistentCookieStore cookieStore = new PersistentCookieStore(this); client.setCookieStore(cookieStore); BasicClientCookie newCookie = new BasicClientCookie("name", "value"); newCookie.setVersion(1); newCookie.setDomain("mycompany.com"); newCookie.setPath("/"); cookieStore.addCookie(newCookie);
AsyncHttpResponseHandler是一个请求返回处理、成功、失败、开始、完成等自定义的消息的类,如上第一个基础例子中所示。
BinaryHttpResponseHandler是继承AsyncHttpResponseHandler的子类,这是一个字节流返回处理的类,用于处理图片等类。
JsonHttpResponseHandler是继承AsyncHttpResponseHandler的子类,这是一个json请求返回处理服务器与客户端用json交流时使用的类。
AsyncHttpRequest继承自Runnable,是基于线程的子类,用于异步请求类, 经过AsyncHttpResponseHandler回调。
PersistentCookieStore继承自CookieStore,是一个基于CookieStore的子类, 使用HttpClient处理数据,而且使用cookie持久性存储接口。
PS:例子用的在牛逼还不如阅读开头列出的官方文档和源码吧。