码迷,mamicode.com
首页 > 移动开发 > 详细

Base-Android快速开发框架(五)--网络操作之RequestModel、ResponeModel、CustomAsyncHttpClient

时间:2015-11-19 16:24:04      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

 在正式介绍CustomAsyncHttpClient之前,刚好最近有一个朋友找我帮忙给他们看下一个APP。我先上一段代码截图。一段检测版本更新的接口代码。

技术分享

 

技术分享

大家也看出问题所在了吧。1.网络操作、数据解析操作的业务出现在了activity。2.没有使用线程池 3.josn的解析,没有面向对象。代码高耦合,复用性差、可靠性差。下面开始进入主题,如何在业务层都看不到json的解析代码了,直接通过CustomAsyncHttpClient拿到目标对象进行操作。

/**
* RequestModel.java
*
* @author: allen
* @Function: 网络请求模型
* @createDate: 2014-8-29
* @update:
*/
public class RequestModel {
private String url;// 请求网络地址
private RequestParams params;// 请求参数
private Class<?> cls;// 请求转换数据模型类
private boolean showDialog = true;// 是否显示网络加载对话框
private boolean showErrorMessage = false;// 是否显示错误的信息

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public RequestParams getParams() {
return params;
}

public void setParams(RequestParams params) {
this.params = params;
}

public Class<?> getCls() {
return cls;
}

public void setCls(Class<?> cls) {
this.cls = cls;
}

public boolean isShowDialog() {
return showDialog;
}

public void setShowDialog(boolean showDialog) {
this.showDialog = showDialog;
}

public boolean isShowErrorMessage() {
return showErrorMessage;
}

public void setShowErrorMessage(boolean showErrorMessage) {
this.showErrorMessage = showErrorMessage;
}

}
/**
* @className:ResponeModel.java
* @author: allen
* @Function: 网络响应模型
* @createDate: 2014-8-29
* @update:
*/
public class ResponeModel {
private Object resultObj;// 转换的Json
private JSONObject dataResult;// 转化为对象的json
private String json;// 服务器返回的整体Json
private Integer code = 0;// 错误码
private boolean status;// 状态
private String msg = "";// 错误信息
private String result = "";// 数据
private int totalCount;// 总条数
private Class<?> cls;// 请求转换数据模型类
private String easyName;// 直接解析的名字
private boolean isList = false;// 是否是数组,默认是对象
private String listCountKey = "totalCount";// 获取总条数的key
private boolean isNew = true;// 是否新的解析
private int buyCount;



public boolean isNew() {
return isNew;
}

public void setNew(boolean isNew) {
this.isNew = isNew;
}

public String getListCountKey() {
return listCountKey;
}

public void setListCountKey(String listCountKey) {
this.listCountKey = listCountKey;
}

public boolean isList() {
return isList;
}

public void setList(boolean isList) {
this.isList = isList;
}

public String getEasyName() {
return easyName;
}

public void setEasyName(String easyName) {
this.easyName = easyName;
}

public Class<?> getCls() {
return cls;
}

public void setCls(Class<?> cls) {
this.cls = cls;
}

public Object getResultObj() {
return resultObj;
}

public void setResultObj(Object resultObj) {
this.resultObj = resultObj;
}

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}

public JSONObject getDataResult() {
return dataResult;
}

public void setDataResult(JSONObject dataResult) {
this.dataResult = dataResult;
}

public String getJson() {
return json;
}

public void setJson(String json) {
this.json = json;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public boolean isStatus() {
return status;
}

public void setStatus(boolean status) {
this.status = status;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
if (StringUtils.isEmpty(msg)) {
this.msg = "服务器发生未知错误!";
} else {
this.msg = msg;
}
}

public int getTotalCount() {
return totalCount;
}

public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}


/**
* 初始化所有数据
*/
public void init() {

initResult();
}

/**
* 获取某一字段
*
* @return
*/
public String parseByName(String name) {
try {
if (!getDataResult().isNull(name)
&& !TextUtils
.isEmpty((getDataResult().get(name).toString()))) {
return (getDataResult().get(name).toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return "";
}

public JSONObject parseJsonToJSONObject(String json) {
try {
return new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new JSONObject(); } }
 /**
* 获取某一字段
*
* @return
*/
public String parseByName(JSONObject object, String name) {
try {
if (!object.isNull(name)
&& !TextUtils.isEmpty((object.get(name).toString()))) {
return (object.get(name).toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return "";
}

/**
* 处理返回的结果,做一些简单的处理
*/
private void initResult() {
if (isStatus()) {
if (getResult() != null && getResult().length() > 0) {
String Head = getResult().substring(0, 1);
// 注:自动快捷解析的情况
// 1.data直接是对象
// 2.data直接是数组(不含条数)
// 3.data直接是对象,对象里面包含“result”数组(条数可选)
// 其它情况均需返回对象,在你的service中进行处理

// Data是对象
if ("{".equals(Head)) {
JSONObject object;
try {
object = new JSONObject(getResult());

setDataResult(object);
if (isList) {
// 带分页
setResultObj(JsonUtil.convertJsonToList(
object.get(getEasyName()).toString(),
getCls()));
if (!object.isNull(getListCountKey())) {// list
// 带总条数
try {
setTotalCount(Integer.parseInt(object
.getString(getListCountKey())));
} catch (Exception e) {
// TODO: handle exception
setTotalCount(0);
}
// 设置其他分页信息
}
return;
}


setResultObj(JsonUtil.convertJsonToObject(
getResult(), getCls()));

} catch (Exception e) {
e.printStackTrace();
}

} else if ("[".equals(Head)) {// data是数组
setResultObj(JsonUtil.convertJsonToList(getResult(),
getCls()));
}
}
}
}
}

RequestModel、ResponeModel封装了网络操作的输入模型和输出模型。RequestModel根据AsyncHttpClient的输入要求做的封装,同时可以控制是否要显示服务器的错误提示信息,是否弹出对话框。ResponeModel封装了业务层所需要的实体对象。接下来看下关键的CustomAsyncHttpClient处理。

public class CustomAsyncResponehandler extends AsyncHttpResponseHandler {

private CustomAsyncResponehandler customAsyncResponehandler;

public CustomAsyncResponehandler() {
customAsyncResponehandler = null;
}

public CustomAsyncResponehandler(
CustomAsyncResponehandler customAsyncResponehandler) {
if (customAsyncResponehandler != null)
this.customAsyncResponehandler = customAsyncResponehandler;
}

public void onSuccess(ResponeModel baseModel) {
if (customAsyncResponehandler != null)
customAsyncResponehandler.onSuccess(baseModel);
}

@Override
public void onStart() {
super.onStart();
if (customAsyncResponehandler != null)
customAsyncResponehandler.onStart();
}

@Override
public void onFinish() {
super.onFinish();
if (customAsyncResponehandler != null)
customAsyncResponehandler.onFinish();
}

@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
if (customAsyncResponehandler != null)
customAsyncResponehandler.onFailure(error, content);
}
}


public class CustomAsyncHttpClient {
private String TAG = "CustomAsyncHttpClient";
private boolean isTag = true;

private AsyncHttpClient asyncHttpClient;
private MyProgressDialog dialog;
private Context mContext;
private ResponeModel baseModel;

public CustomAsyncHttpClient(Context context) {
asyncHttpClient = new AsyncHttpClient();
mContext = context;
if (mContext != null) {
dialog = new MyProgressDialog(mContext, "", true);
dialog.tv_value.setVisibility(View.GONE);
}
baseModel = new ResponeModel();
}

public void post(final RequestModel requestModel,
final CustomAsyncResponehandler responseHandler) {

RequestParams newParams = new RequestParams();
com.alibaba.fastjson.JSONObject jsonObject = new
com.alibaba.fastjson.JSONObject();
for (BasicNameValuePair param :
requestModel.getParams().getParamsList()) {
jsonObject.put(param.getName(), param.getValue());
}
newParams.fileParams=requestModel.getParams().fileParams;

newParams.put("p", jsonObject.toString());


LogUtil.d(TAG, requestModel.getUrl() + "?"
+ newParams.toString(), isTag);
asyncHttpClient.post(requestModel.getUrl(), newParams,
new AsyncHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
LogUtil.d(TAG, "onStart___", isTag);
if (requestModel.isShowDialog()) {// 显示网络对话框
if (mContext != null) {
dialog.show();
}
}
responseHandler.onStart();
}

@Override
public void onFinish() {
super.onFinish();
LogUtil.d(TAG, "onFinish___", isTag);
if (requestModel.isShowDialog()) {// 隐藏网络对话框
if (mContext != null) {
dialog.dismiss();
}
}
responseHandler.onFinish();
}

@Override
public void onSuccess(String content) {
super.onSuccess(content);
LogUtil.d(TAG, "onSuccess___" + content, isTag);

// TODO:解密返回的参数
baseModel = JsonUtil.convertJsonToObject(content,
ResponeModel.class);

if (baseModel != null) {
baseModel.setCls(requestModel.getCls());
baseModel.setJson(content);
baseModel.init();
if(baseModel.isStatus()){
baseModel.setMsg("操作成功");
}
}

if (requestModel.isShowErrorMessage()&&!baseModel.isStatus()) {
if (mContext != null) {
UIHelper.ShowMessage(mContext,
baseModel.getMsg());
}
}

responseHandler.onSuccess(baseModel);
}

@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
LogUtil.d(TAG, "onFailure___" + content, isTag);
if (mContext != null) {
UIHelper.ShowMessage(mContext,
"网络异常");
}
responseHandler.onFailure(error, content);
}
});
}
}

以后无须再为网络操作而操碎心,下一步希望在Base里面加入支持xml的自动对象转换以及webservice服务器调用的封装支持,希望有兴趣的、或者有更好方案的大神联系我。下面再上一下上一节的使用案例,网络操作的登陆方法:

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);
}
});
}

Base-Android快速开发框架(五)--网络操作之RequestModel、ResponeModel、CustomAsyncHttpClient

标签:

原文地址:http://www.cnblogs.com/huangjunbin/p/4977852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!