android-async-http开源网络框架是专门针对Android在Apache的基础上构建的异步且基于回调的http client。所有的请求全在UI线程之外发生,而callback发生在创建它的线程中,应用了Android的Handler发送消息机制。
android-async-http的特点:(这段摘自网络)
- Make asynchronous HTTP requests, handle responses in anonymous callbacks
- 进行异步HTTP请求,处理响应在匿名回调中完成
- HTTP requests happen outside the UI thread
- HTTP请求发生在UI线程之外
- Requests use a threadpool to cap concurrent resource usage
- 请求使用threadpool,限制并发资源使用情况
- GET/POST params builder (RequestParams)
- GET / POST参数构建使用(RequestParams)
- Multipart file uploads with no additional third party libraries
- Multipart 文件上传,没有额外的第三方库
- Tiny size overhead to your application, only 25kb for everything
- 在你的应用程序上利用很小的开销,仅仅25 kb就可以做一切
- Automatic smart request retries optimized for spotty mobile connections
- 自动智能请求重试,优化了质量不一的移动连接
- Automatic gzip response decoding support for super-fast requests
- 自动解码支持gzip反应速度超快的请求
- Binary file (images etc) downloading with BinaryHttpResponseHandler
- 二进制文件(图片等)的下载,使用BinaryHttpResponseHandler
- Built-in response parsing into JSON with JsonHttpResponseHandler
- 内置响应解析成JSON,使用JsonHttpResponseHandler
- Persistent cookie store, saves cookies into your app’s SharedPreferences
- 持久化cookie存储,保存cookie到你的应用程序的SharedPreferences
android-async-http开源库下载地址:https://github.com/loopj/android-async-http
基本用法:
将下载好的的android-async-http开源库压缩包解压,打开文件夹如下图所示:
打开"releases"文件夹,里面后各个版本的jar包。如图:
接着新建一个Android工程,取名为"zhj_async_http"。将1.4.5版本的jar包导入并添加到工程中,如图:
接下来就是敲代码了。
先来一个最简单的用法(请求百度页面):
Import the http package.
import com.loopj.android.http.*;
Create a new AsyncHttpClient instance and make a request:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.baidu.com", 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); } } );
整个步骤如下:
1、创建一个AsyncHttpClient对象。
2、用这个对象设置请求方式(包括get、put、post、head、delete)。
3、传入参数(包括请求地址、参数的设置、并指定一个ResponseHandlerInterface的实例接收请求结果)。
4、在onSuccess()方法中执行请求成功的操作,在onFailure()方法中执行请求失败的操作。
怎么样?是不是感觉很简单?
不过官方建议使用静态的方式,官方Demo:
import com.loopj.android.http.*; 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; } }
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); } }); } }
那么,现在来使用android-async-http开源框架来实现获取String字符串、Json格式的数据和网络图片。
首先根据官方建议使用static实现一个HttpUtil.java(目前只使用get请求方式):
public class HttpUtil { private static AsyncHttpClient client = new AsyncHttpClient(); // 实例话对象 static { client.setTimeout(11000); // 设置链接超时,如果不设置,默认为10s } public static AsyncHttpClient getClient() { return client; } public static void get(String urlString, AsyncHttpResponseHandler res) // 用一个完整url获取一个string对象 { client.get(urlString, res); } public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) // url里面带参数 { client.get(urlString, params, res); } 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); } }
布局文件的实现:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/iv" android:layout_width="300dp" android:layout_height="300dp" /> <ScrollView android:id="@+id/sl" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" /> </ScrollView> </LinearLayout>
接下来是MainActivity.java(三个方法分别是实现获取Json(包括JSONObject和JSONArray)、String、网络图像)
public class MainActivity extends Activity { private TextView tv; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); iv = (ImageView) findViewById(R.id.iv); Json(); String(); image(); } private void image() { AsyncHttpClient client = new AsyncHttpClient(); client.get( "http://b.hiphotos.baidu.com/zhidao/pic/item/d833c895d143ad4b08c2629580025aafa50f06f2.jpg", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if (statusCode == 200) { BitmapFactory factory = new BitmapFactory(); Bitmap bitmap = factory.decodeByteArray( responseBody, 0, responseBody.length); iv.setImageBitmap(bitmap); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(); } }); } private void String() { HttpUtil.get("http://www.baidu.com", new TextHttpResponseHandler() { @Override public void onSuccess(int arg0, Header[] arg1, String arg2) { tv.setText(arg2); } @Override public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) { tv.setText("请求百度失败"); } }); } private void Json() { HttpUtil.get("http://m.weather.com.cn/data/101010100.html", new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // TODO Auto-generated method stub super.onSuccess(statusCode, headers, response); if (statusCode == 200) { try { String str = response.getJSONObject( "weatherinfo").getString("index_d"); tv.setText(str); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { tv.setText("statusCode != 200"); } } }); } }
运行结果如下图:
(左图是网络图像加String,右图是网络图像加Json数据)
参考博客:http://www.open-open.com/lib/view/open1369637365753.html
相关博客:http://www.cnblogs.com/angeldevil/p/3729808.html
官方文档:http://loopj.com/android-async-http/
代码比较简单就不附上DEMO了。