Async-http-client第三方开源类库,主要针对Android开发中发送http请求的。从名字Async中就知道它是异步操作,在非UI线程中执行,请求时不需要其他处理,用起来十分方便。
需要这两个.jar包。android-async-http-1.4.9.jar 和 httpclient-4.4.1.1.jar SDK6.0之后只需要前面那个架包。
官方下载地址:http://loopj.com/android-async-http/
对应的github地址:https://github.com/loopj/android-async-http
也可以到我的博客资源库去下载:http://download.csdn.net/detail/tom_xiaoxie/9301799
<span style="white-space:pre"> </span>AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is "200 OK" } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried } });
AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); client.get("http://www.google.com", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { System.out.println(response); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Log.d("ERROR", error); } });
上面的例子返回的response直接是原生字节流的形式,如果你需要把返回的结果当成一个String对待的话,之间转换时一种方式。这么强大的工具怎么会没有想到我们的需求呢?只需改变你的回调对象即可,TextHttoResponseHandler,其是继承自AsyncHttpResponse,它将原生的字节流根据指定的encoding转化成了String对象了。
AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); client.get("http://www.google.com", params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { System.out.println(response); } @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) { Log.d("ERROR", error); } } );同样的方式,你也可以发送JSON请求。 JsonHttpResponseHandler匿名类。返回的Response直接以JSONObject的形式返回,也支持JSONArray的形式,你只需要Override你需要的版本就可以
String url = "http://192.168.1.112:8080/app/page?PageNo="+pageNo+"&PageSize=20"; AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("q", "android"); params.put("rsz", "8"); client.get(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // Handle resulting parsed JSON response here } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { // Handle resulting parsed JSON response here } });