标签:
在使用异步请求网络数据时,每次请求一个接口就定义一个异步类,为避免其中一些多余的步骤,采用将异步类抽象出来
以下使用一个登陆接口来对比使用接口的前后,登陆使用post请求
简化前异步的实现:
class LoginAsyTask extends AsyncTask<Void, Integer, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0) {
//post请求的参数
Map<String, String> params = new HashMap<String, String>();
params.put("username", mEditUserName.getText().toString());
params.put("password", mEditUserPwd.getText().toString());
try {
//发送请求,接受服务器返回的字符串
return PostUtil.sendPostRequest(loginUrl,params);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if(result != null){
JSONTokener jsonParser = new JSONTokener(result);
// 此时还未读取任何json文本,直接读取就是一个JSONObject对象。
JSONObject loginJSON;
try {
loginJSON = (JSONObject) jsonParser.nextValue();
// 接下来的就是JSON对象的操作了
loginJSON.getString("message");
loginJSON.getInt("code");
if(loginJSON.getInt("code") == 0){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "登录成功", 0).show();
}else{
Toast.makeText(LoginActivity.this, "登录失败", 0).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogUtil.e("login", result.toString());
}
super.onPostExecute(result);
}
}
将异步使用接口简化后
首先定义一个接口,其中包括一个抽象的onPostExecute(Object object)方法
AsyncCallBack.Class
public interface AsyncCallBack {
public void onPostExecute(Object object);
}
然后定义一个异步的抽象类
public abstract class AbstractPostAsyncTask<Void, Progress, Result> extends AsyncTask<Void, Progress, Result>{
private HttpUtil mHttpUtil;
private Gson gson;
private Class<Result> result;
protected AsyncCallBack mAsyncCallBack;
public AbstractPostAsyncTask(Class<Result> t, AsyncCallBack asyncCallBack) {
this.mAsyncCallBack = asyncCallBack;
this.result = t;
this.gson = new Gson();
this.mHttpUtil = new HttpUtil();
}
@Override
protected Result doInBackground(Void... arg0) {
String str = null;
try {
str = PostUtil.sendPostRequest(getRequestUrl(), getRequestParams());
return parse(str, result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
this.mAsyncCallBack.onPostExecute(result);
}
private Result parse(String str, Class<Result> t) {
Result result = null;
ObjectMapper mapper = MapperUtil.getMapper();
//解析Json数据为“申请”对象
try {
result = mapper.readValue(str,t);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected abstract Map<String, String> getRequestParams();
protected abstract String getRequestUrl();
}
最后在需要的地方实现这个抽象类的抽象方法和AsyncCallBack接口中的onPostExecute(Object object)方法
public class AllSitesAsyTask extends AbstractGetAsyncTask<Void, Void, SiteJSON> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
public AllSitesAsyTask(Class<LOGINJSON> t, AsyncCallBack asyncCallBack) {
super(t, asyncCallBack);
}
@Override
public String getRequestUrl() {
return Constants.LOGIN_URL;
}
}
实现异步的执行
AllSitesAsyTask allSitesAsyTask = new AllSitesAsyTask(SiteJSON.class, new AsyncCallBack() {
@Override
public void onPostExecute(Object object) {
setAllStationToList(object);
progressDialog.dismiss();
}
});
allSitesAsyTask.execute();
使用到的PostUtil工具类,用来请求post数据
public class PostUtil {
/**
*
* @param params 参数数组
* @return
*/
public static String sendPostRequest(String url, Map<String, String> params) throws ClientProtocolException, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>(); //存放请求参数
if(params != null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
return EntityUtils.toString(response.getEntity());
}
return null;
}
}
标签:
原文地址:http://www.cnblogs.com/z-xiaoqiang/p/4537805.html