* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hiimeloyun.android.process;
import android.os.AsyncTask;
import com.hiimeloyun.android.core.App;
import com.hiimeloyun.android.core.Constants.HttpMethod;
import com.hiimeloyun.android.core.ParamArray;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author boroo
*/
public class HttpAsyncTask extends AsyncTask<Void, Void, JSONObject> {
private static CookieStore cookieStore = new BasicCookieStore();
private HttpMethod httpMethod;
private String action;
private ParamArray paramArray;
private Object tag;
protected String registerName;
protected HttpTaskListener listener;
protected Exception error;
protected String currentUrl;
public HttpAsyncTask(HttpMethod httpMethod) {
this(httpMethod, null);
}
public HttpAsyncTask(HttpMethod httpMethod, String registerName) {
this.httpMethod = httpMethod;
this.registerName = registerName;
}
// -----------------------------------------------------------------------
public HttpMethod getHttpMethod() {
return this.httpMethod;
}
public String getRegisterName() {
return this.registerName;
}
public Exception getError() {
return this.error;
}
public String getCurrentUrl() {
return this.currentUrl;
}
// -----------------------------------------------------------------------
public void setAction(String action) {
this.action = action;
}
public String getAction() {
return this.action;
}
public void setParamArray(ParamArray paramArray) {
this.paramArray = paramArray;
}
public ParamArray getParamArray() {
return this.paramArray;
}
public void setTag(Object tag) {
this.tag = tag;
}
public Object getTag() {
return this.tag;
}
// -----------------------------------------------------------------------
public boolean hasError() {
return (this.error != null);
}
public void setListener(HttpTaskListener listener) {
this.listener = listener;
}
public void cancel() {
this.cancel(true);
}
// -----------------------------------------------------------------------
@Override
protected void onPreExecute() {
App.tasks.register(this);
error = null;
switch (httpMethod) {
default:
case GET:
currentUrl = App.util.combineUri(App.util.buildUri(action), paramArray);
break;
case POST:
currentUrl = App.util.buildUri(action);
break;
case PUT:
currentUrl = App.util.buildUri(action);
break;
case DELETE:
currentUrl = App.util.combineUri(App.util.buildUri(action), paramArray);
break;
}
if (listener != null) {
listener.OnTaskStarted(this);
}
}
protected JSONObject doInBackground(Void... params) {
JSONObject jsonResult = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpRequestBase request;
UrlEncodedFormEntity passEntity = null;
if (paramArray.size() > 0) {
passEntity = new UrlEncodedFormEntity(paramArray, HTTP.UTF_8);
}
switch (httpMethod) {
default:
case GET:
request = new HttpGet(currentUrl);
break;
case POST:
request = new HttpPost(currentUrl);
if (passEntity != null) {
((HttpPost) request).setEntity(passEntity);
}
break;
case PUT:
request = new HttpPut(currentUrl);
if (passEntity != null) {
((HttpPut) request).setEntity(passEntity);
}
break;
case DELETE:
request = new HttpDelete(currentUrl);
break;
}
HttpResponse response = httpClient.execute(request, localContext);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String responseText = EntityUtils.toString(entity, HTTP.UTF_8);
if (responseText.startsWith("{\"")) {
jsonResult = new JSONObject(responseText);
} else {
jsonResult = new JSONObject();
jsonResult.put("status", false);
jsonResult.put("error", responseText);
jsonResult.put("html", true);
}
jsonResult.put("statusCode", statusCode);
} catch (IOException ex) {
error = ex;
} catch (ParseException ex) {
error = ex;
} catch (JSONException ex) {
error = ex;
}
return jsonResult;
}
@Override
protected void onPostExecute(JSONObject result) {
App.tasks.remove(this);
int statusCode = 200;
try {
statusCode = result.getInt("statusCode");
} catch (JSONException ex) {
ex.toString();
}
switch (statusCode) {
case 400:
//400 Bad Request
App.notice.Toast("Хүсэлт буруу байна!");
break;
case 401:
//401 Unauthorized
App.notice.Toast("Та дахин нэвтрэн ороорой!");
break;
case 404:
//401 Unauthorized
App.notice.Toast("Мэдээлэл олдсонгүй!");
break;
default:
if (listener != null) {
listener.OnTaskCompleted(result, this, false);
}
}
}
@Override
protected void onCancelled() {
App.tasks.remove(this);
if (listener != null) {
listener.OnTaskCompleted(null, this, true);
}
}
// -----------------------------------------------------------------------
// private List<Cookie> loadCookies() {
// List<Cookie> cookies = new ArrayList<Cookie>();
// try {
// String cookieName = App.config.getItem("cookieName", "shared");
// String cookieString = App.sharedStorage.getString(cookieName);
//
// if (cookieString != null && !cookieString.isEmpty()) {
// JSONObject jsonObject = new JSONObject(cookieString);
// Iterator<String> iterator = jsonObject.keys();
// while (iterator.hasNext()) {
// String key = iterator.next();
// String val = jsonObject.getString(key);
//
// List<HttpCookie> cookieList = HttpCookie.parse(val);
// for (HttpCookie httpCookie : cookieList) {
// BasicClientCookie basicClientCookie = new BasicClientCookie(httpCookie.getName(), httpCookie.getValue());
// basicClientCookie.setSecure(httpCookie.getSecure());
// basicClientCookie.setDomain(httpCookie.getDomain());
// basicClientCookie.setPath(httpCookie.getPath());
// basicClientCookie.setVersion(httpCookie.getVersion());
// long time = new Date().getTime() + httpCookie.getMaxAge();
// basicClientCookie.setExpiryDate(new Date(time));
// cookies.add(basicClientCookie);
// }
// }
// }
// } catch (Exception ex) {
// this.error = ex;
// }
// return cookies;
// }
//
// private void saveCookies(List<Cookie> cookies) {
// try {
// String cookieName = App.config.getItem("cookieName", "shared");
// Editor editor = App.sharedStorage.editor();
//
// if (!cookies.isEmpty()) {
// JSONObject jsonObject = new JSONObject();
// for (Cookie cookie : cookies) {
// if (cookie.getName().length() > 0) {
// jsonObject.put(cookie.getName(), cookie.toString());
// }
// }
// editor.putString(cookieName, jsonObject.toString()).commit();
// }
// } catch (Exception ex) {
// this.error = ex;
// }
// }
}
No comments:
Post a Comment