开发android app 需要进行获取网络数据或者向服务器发送数据操作,这些数据传送可以通过android-async-http开源框架来帮我实现。android-async-http使用起来也很简单。
android-async-http 项目主页:https://github.com/loopj/android-async-http 可供下载源代码和jar包。
在Android项目中添加jar包值lib或者在build.gradle中添加如下依赖
dependencies { XXXXXXX //android-async-http compile 'com.loopj.android:android-async-http:1.4.8' }
此时就可以使用android-async-http获取网络上的数据了。
public class HttpUtil { private static AsyncHttpClient client = new AsyncHttpClient(); static { client.setTimeout(15000); // 超时时间,默认为10s DEFAULT_SOCKET_TIMEOUT = 10 * 1000; } public static void get(String url, AsyncHttpResponseHandler res) { client.get(url, res); } public static void get(String url, RequestParams params, AsyncHttpResponseHandler res) { client.get(url, params, res); } public static void get(String url, JsonHttpResponseHandler res) { client.get(url, res); } public static void get(String url, RequestParams params, JsonHttpResponseHandler res) { client.get(url, params, res); } public static void get(String url, BinaryHttpResponseHandler bHandler) { client.get(url, bHandler); } public static void post(String url, AsyncHttpResponseHandler res) { client.post(url, res); } public static void post(String url, RequestParams params, AsyncHttpResponseHandler res) { client.post(url, params, res); } public static void post(String url, JsonHttpResponseHandler res) { client.post(url, res); } public static void post(String url, RequestParams params, JsonHttpResponseHandler res) { client.post(url, params, res); } public static AsyncHttpClient getClient() { return client; } }
RequestParams params = new RequestParams();
params.put(“key", "value");//通过键值对的方式添加需要的参数
String url = "http://hostname:8088/your_url";
HttpUtil.get(url , params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray object) {//这里可根据返回数据决定是array还是objec
super.onSuccess(statusCode, headers, object);
Log.v("SearchActivity", object.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,
JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,
JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString,
Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
}
});
因为我们的操作用到了网络进行数据传输。所以我们的app需要网络权限,在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.INTERNET" />
是不是很简单,现在就可以专心处理我们所需要的数据了。