FastJson和AsyncHttpCLient
Android的展示数据,除了上章所讲的本地存储外,大部分数据都来自于网络。首先介绍一下Android APP开发常见的网络操作方式。从网络层面上有底层的tcp/ip,也就是我们常见的socket套接字,常见于IM、消息推送等应用场景。另外常见的就是Http协议、webservice协议,常用于提供数据接口。常应用的数据格式有xml、json。其中最常见的也就是Http+Json的组合,这也是我们接下来要讲解的重点。在这么多项目的累计中,对于Http的访问,我用过HttpUtil这样的工具类,当然里面封装了简单的get post方法。另外也用过volley这样的集成框架。现在向大家推荐下我觉得最好用的一个框架就是AsyncHttpClient。先上一段简单的示例代码。
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
}
});
全在UI线程之外发生,而callback发生在创建它的线程中,应用了Android的Handler发送消息机制。你也可以把AsyncHttpClient应用在Service中或者后台线程中,库代码会自动识别出它所运行的context。github下载地址:https://github.com/loopj/android-async-http 。库的size很小,所有的一切只有90kb,发送异步http请求,在匿名callback对象中处理response,http请求发生在UI线程之外,内部采用线程池来处理并发请求。详细可以度娘一下。
public final class JsonUtil {
private static String TAG = "FastJson";
public static boolean isSuccess(String jsonString) {
JSONObject json;
boolean flag = false;
try {
json = new JSONObject(jsonString);
flag = json.getBoolean("result");
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
public static String getArrayString(String jsonString, String key) {
String value = "";
JSONObject json;
try {
json = new JSONObject(jsonString);
value = json.getJSONArray(key).toString();
} catch (JSONException e) {
e.printStackTrace();
}
return value;
}
public static String convertObjectToJson(Object o) {
SerializerFeature[] features = { SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteSlashAsSpecial,
SerializerFeature.BrowserCompatible,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat };
try {
Log.d(TAG, JSON.toJSONString(o, features));
return JSON.toJSONString(o, features);
} catch (Exception e) {
Log.e(TAG, e.toString());
return "";
}
}
public static <T> T convertJsonToObject(String json, Class<T> clazz) {
try {
return JSON.parseObject(json, clazz);
} catch (Exception e) {
Log.e(TAG, e.toString());
Log.e("merror", e.toString());
return null;
}
}
public static <T> List<T> convertJsonToList(String json, Class<T> clazz) {
try {
return JSON.parseArray(json, clazz);
} catch (Exception e) {
Log.e(TAG, e.toString());
System.out.println(e.toString());
return null;
}
}
}
到这里大家是不是以为就结束了,当然不是,还能更easy。下节将介绍自己封装的CustomAsyncHttpClientCustomAsyncResponehandler。将这两个框架整合,先上一段代码:
网络操作的登陆方法:
public void login(final String userName, final String password, final CustomAsyncResponehandler handler) {
RequestModel requestModel = new RequestModel();
RequestParams params = new RequestParams();
params.put("userName", userName);
params.put("password", password);
requestModel.setParams(params);
requestModel.setCls(User.class);
requestModel.setShowErrorMessage(true);
requestModel.setUrl(Urls.userLogin);
httpClient.post(requestModel, new CustomAsyncResponehandler() {
@Override
public void onSuccess(ResponeModel baseModel) {
super.onSuccess(baseModel);
if (baseModel != null && baseModel.isStatus()) {
AppContext.currentUser = (User) baseModel.getResultObj();
AppContext.currentUser.setUserName(userName);
if (userDao != null) {
userDao.insert(AppContext.currentUser);
}
}
handler.onSuccess(baseModel);
}
});
}
在业务层都看不到json的解析代码了,直接通过CustomAsyncHttpClient拿到目标对象进行操作。