本章节主要介绍xUtils3.x架构POST网络请求同步和异步的两种用法:
首先对RequestParams对象进行封装,设置公共请求头,cookie,超时等,如下所示。
/**
* 封装xutils的RequestParams
* Created by wangpf on 2017/8/19.
*/
public class NetParams extends RequestParams {
public NetParams(String url, int timeOut){
super(AppHelper.HTTPRUL+url);
setConnectTimeout(timeOut==0?30*1000:timeOut);
addHeader("Type","android");
long timestamp = System.currentTimeMillis()/1000;
addHeader("Timestamp", timestamp+"");
......
//设置cookie
if (!"f/app/user/login".equals(url)) { //登陆 和不需要cookie的接口
SharedPreferences sharedPreferences = x.app().getSharedPreferences(Constants.SHAREDNAME, Context.MODE_PRIVATE);
AppHelper.Cookie = sharedPreferences.getString("jsessionid", "");
addHeader("Cookie", "JSESSIONID="+AppHelper.Cookie);
setUseCookie(false);
}else{
setUseCookie(true);
}
}
}
(1)异步POST请求,很简单直接上代码
NetParams params = new NetParams("a/app/user/login", 0);
x.http().post(params, new Callback.CommonCallback() {
@Override
public void onCancelled(CancelledException arg0) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
if(ex instanceof HttpException) { // 网络错误
mHandler.obtainMessage(MSG_ERROR, "网络异常,请检查后重试").sendToTarget();
}else if (ex instanceof SocketTimeoutException){ // 其他错误
mHandler.obtainMessage(MSG_ERROR, "网络请求超时,请检查后重试").sendToTarget();
}else {
mHandler.obtainMessage(MSG_ERROR, "用户登录失败,请检查后重试").sendToTarget();
}
}
// 不管成功或者失败最后都会回调该接口
@Override
public void onFinished() {
}
@Override
public void onSuccess(String msg) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(msg);
// TODO 业务处理
}catch(JSONException e) {
Log.e("evmsapp", e.getMessage());
mHandler.obtainMessage(MSG_ERROR, "用户登录失败,请检查后重试").sendToTarget();
}
}
});
JsonResponseParser解析器,实现接口ResponseParser。
import com.alibaba.fastjson.JSON;
import com.llg.utils.StringUtils;
import java.lang.reflect.Type;
import org.json.JSONObject;
import org.xutils.http.app.ResponseParser;
import org.xutils.http.request.UriRequest;
/**
* 使用ResponseParser自动解析定义的请求结果
* Created by wangpf on 2017/8/16.
*/
public class JsonResponseParser implements ResponseParser {
public Object parse(Type resultType, Class> resultClass, String result) throws Throwable {
try {
if(StringUtils.isEmpty(result)) {
return null;
}
new JSONObject(result);
}catch (Exception e) {
e.printStackTrace();
return null;
}
return JSON.parseObject(result, resultClass);
}
public void checkResponse(UriRequest request) throws Throwable {
}
}
import org.xutils.http.annotation.HttpResponse;
import java.util.List;
/**
* 接收同步网络请求结果
* Created by wangpf on 2017/8/16.
*/
@HttpResponse(parser = JsonResponseParser.class)
public class ResponseMaintainBean extends ResponseBean {
private List data;
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
}
try {
NetParams params = new NetParams("a/app/maintain/list", 0);
params.addBodyParameter("carFrame", carFrame);
int pageNo = (int)(start/limit)+1;
params.addBodyParameter("pageNo", pageNo+"");
params.addBodyParameter("pageSize", limit+"");
//这里就是使用同步请求的地方了,只有一句代码,可以直接返回一个对象。
ResponseMaintainBean responseBean = x.http().postSync(params, ResponseMaintainBean.class);
if(responseBean != null) {
//TODO 业务处理
}else {
msgHandler.obtainMessage(EXCEPTION, "获取xxxx信息失败,请检查后重试").sendToTarget();
}
}catch (Throwable throwable) {
throwable.printStackTrace();
if(throwable instanceof HttpException) { // 网络错误
msgHandler.obtainMessage(EXCEPTION, "网络异常,请检查后重试").sendToTarget();
}else if (throwable instanceof SocketTimeoutException){ // 其他错误
msgHandler.obtainMessage(EXCEPTION, "网络请求超时,请检查后重试").sendToTarget();
}else {
msgHandler.obtainMessage(EXCEPTION, "获取xxxx信息失败,请检查后重试").sendToTarget();
}
}