官网介绍: http://loopj.com/android-async-http/
git仓库:https://github.com/loopj/android-async-http
android-async-http最简单使用:
1.获取一个AsyncHttpClient对象
AsyncHttpClient client = new AsyncHttpClient();
2.调用AsyncHttpClient的get或者post方法,实现回调方法AsyncHttpResponseHandler
AsyncHttpClient类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类ResponseHandlerInterface方法处理。
带参数的使用方法:
get:
通过RequestParams类添加参数
RequestParams params = new RequestParams(); params.put("", ""); client.get("http://www.baidu.com", params, new AsyncHttpResponseHandler() { @Override @Deprecated public void onFailure(Throwable error) { super.onFailure(error); Log.e(TAG, "onFailure"); } @Override public void onFinish() { super.onFinish(); Log.e(TAG, "onFinish"); } @Override public void onStart() { super.onStart(); Log.e(TAG, "onStart"); } @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { super.onSuccess(arg0, arg1, arg2); Log.e(TAG, "onSuccess"); String string = new String(arg2); tv_context.setText(string); } });
下面是上传图片到服务器
RequestParams params = new RequestParams();
params.put("file_path", new File(file_path));
RequestParams params = new RequestParams(); params.put("file_path", new File(file_path)); client.post(url, params, 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 onProgress(int bytesWritten, int totalSize) { super.onProgress(bytesWritten, totalSize); } });
onProgress方法中可以添加进度显示操作
那么每次请求是不是都要获取一遍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; } }
更多详细的的使用方法可以参考官方的文档:http://loopj.com/android-async-http/
因为是异步网络请求框架,当然不要忘记了网络权限:
<uses-permission android:name="android.permission.INTERNET" />