android-async-http使用总结

来源:互联网 发布:数据库物理设计实例 编辑:程序博客网 时间:2024/05/16 15:14

其实apache还是提供了释放 连接资源的方法的,不过是埋得深了点。 

?
1
httpClient.getConnectionManager().shutdown();

这个shutdown并不是将手机网络断掉,而是将建立Http连接请求时所分配的资源释放掉。





下载最新的包可以到github:https://github.com/loopj/android-async-http

官方说明文档:http://loopj.com/android-async-http

将jar包添加到项目里面就可以开始使用了:
第一步:
按照官方推荐,创建一个静态的请求对象.添加基本请求功能
public class MyBaseRequest {public static AsyncHttpClient client = new AsyncHttpClient(); // 实例话对象static {client.setTimeout(10000); // 设置链接超时,如果不设置,默认为10s}public static void post(Context context,String url, RequestParams params,AsyncHttpResponseHandler handler) {client.post(context,url, params,handler);}public static void get(String urlString, JsonHttpResponseHandler res) // 不带参数,获取json对象或者数组{client.get(urlString, res);}public static void get(String urlString, RequestParams params,JsonHttpResponseHandler res) // 带参数,获取json对象或者数组{client.get(urlString, params, res);}public static void get(String uString, BinaryHttpResponseHandler bHandler) // 下载数据使用,会返回byte数据{client.get(uString, bHandler);}public static AsyncHttpClient getClient() {return client;}

以上只列举了get和post这两种请求方式的常用方法,一般这两个方法就够用了,详细方法可以去官网查看。
第二步,发起请求
MyBaseRequest.post(context,url,params,new AsyncHttpResponseHandler() {@Overridepublic void onStart() {super.onStart();System.out.println("start"+url);}@Overridepublic void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable throwable) {}@Overridepublic void onFinish() {// TODO Auto-generated method stubsuper.onFinish();}});

一共有四个回调的方法分别是 发起请求、请求成功、请求失败、请求完成。不管请求失败还是成功都会调用请求完成这个方法。
在请求成功是得到的byte[]我们可以通过String(bytes, "UTF-8")这个方法将它转换成String类型的字符串。也可以调用可以直接返回String类型数据的post或者get方法。
第三步:将cookie保存在本地
public static PersistentCookieStore myCookieStore = new PersistentCookieStore(BaseApplication.getApplication().getApplicationContext());public static AsyncHttpClient client = new AsyncHttpClient(); // 实例话对象static {client.setTimeout(10000); // 设置链接超时,如果不设置,默认为10s}public static RequestHandle post(Context context,String url, RequestParams params,AsyncHttpResponseHandler handler) {client.setCookieStore(myCookieStore);client.setMaxRetriesAndTimeout(0, 10000);// 固定的请求头设置return client.post(context,url, params,handler);}

通过以上代码的设置,任何从服务器端获取的cookie都会持久化存储到myCookieStore中。
也可以在cookie中添加我们自定义的数据,如下:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");newCookie.setVersion(1);newCookie.setDomain("mydomain.com");newCookie.setPath("/");myCookieStore.addCookie(newCookie);

第三步:取消发送的请求
android-async-http能被取消请求的请求必须传入一个Context,否则则没有任何效果。
实例代码如下:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btn_one = (Button) findViewById(R.id.btn_one);btn_one.setOnClickListener(this);Button btn_two = (Button) findViewById(R.id.btn_two);btn_two.setOnClickListener(this);RequestParams params = new RequestParams();System.out.println("请求一开始");requestOne(this,"http://blog.csdn.net/hil2000/article/details/13949513",params);//requestOne.cancel(true);System.out.println("请求二开始");requestTwo(this,"http://www.ithao123.cn/content-2670929.html",params);//requestTwo.cancel(true);MyBaseRequest.client.cancelAllRequests(true);}private void requestOne(Context context,final String url,final RequestParams params) {requestOne = MyBaseRequest.post(context,url,params,new AsyncHttpResponseHandler() {@Overridepublic void onStart() {super.onStart();System.out.println("start"+url);}@Overridepublic void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {try {String info = MyBaseRequest.getStringFromByte(responseBody);System.out.println("请求 One 的结果");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable throwable) {System.out.println("请求 One 失败");}});}private void requestTwo(Context context,final String url,final RequestParams params) {requestTwo = MyBaseRequest.post(context,url,params,new AsyncHttpResponseHandler() {@Overridepublic void onStart() {super.onStart();System.out.println("start"+url);}@Overridepublic void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {try {String info = MyBaseRequest.getStringFromByte(responseBody);System.out.println("请求 Two 的结果");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable throwable) {System.out.println("请求 Two 失败");}});}

本框架一共提供了三中取消请求的方法:
1.cancelRequests(Context context, boolean mayInterruptIfRunning);//在AsyncHttpClient中
2.cancelAllRequests(boolean mayInterruptIfRunning);//在AsyncHttpClient中
3.cancel(boolean mayInterruptIfRunning) //在RequestHandle中
在本例中使用了第二种和第三种。第一种(cancelRequests)和第二种(cancelAllRequests)的效果是一样的,都用来取消全部请求。而第三种取消方式(cancel(boolean mayInterruptIfRunning) //在RequestHandle中)是用来取消单个请求的。
    转载请注明出处:http://renyuan-1991.iteye.com/blog/2249325
0 1
原创粉丝点击