The android-async-http open-source framework allows us to easily obtain network data or send data to servers. The most important thing is that it is an asynchronous framework that uses a thread pool at the underlying layer to process concurrent requests, highly efficient and easy to use.
In the past, we used to build projects on Android, such as downloading many images, webpages, or other resources. Most developers choose a thread and a download task model, because Android's AndroidHttpClient or java's java.net. URL, which is a blocking operation by default. This model is inefficient and does not apply to apps with high concurrency requirements. Some people will choose to use nio for their own implementation, and the Code complexity is high.
AsyncHttpClient is a core application class of the android-async-http framework. It is easy to use and can process web resources in various formats such as text and binary. The following code shows how to use it:
public class Downloader { public static AsyncHttpClient mHttpc = new AsyncHttpClient(); public static String TAG = "Downloader"; public void downloadText(String uri){ mHttpc.get(uri, null, new AsyncHttpResponseHandler(){ @Override public void onSuccess(String data){ Log.i(TAG, "downloaded, thread id " + Thread.currentThread().getId()); // TODO: do something on } @Override public void onFailure(Throwable e, String data){ Log.i(TAG, "download failed."); // TODO: error proceed } }); } public void downloadImage(String uri, String savePath){ mHttpc.get(uri, new ImageResponseHandler(savePath)); } public class ImageResponseHandler extends BinaryHttpResponseHandler{ private String mSavePath; public ImageResponseHandler(String savePath){ super(); mSavePath = savePath; } @Override public void onSuccess(byte[] data){ Log.i(TAG, "download image, file length " + data.length); // TODO: save image , do something on image } @Override public void onFailure(Throwable e, String data){ Log.i(TAG, "download failed"); // TODO : error proceed } }};
The code above demonstrates how to use AsyncHttpResponseHandler and BinaryHttpResponseHandler. I believe AsyncHttpClient will bring great convenience to you.