標籤:android 應用開發 asynchttpclient
網路請求是所有App都必不可少的功能,如果每次開發都重寫一次網路請求或者將以前的代碼複製到新的App中,不是很合理,出於此目的,我希望將整個網路請求架構獨立出來,與商務邏輯分隔開,這樣就可以避免每次都要重新編寫網路請求,於是基於我比較熟悉的asynchttpclient重新二次封裝了一個網路請求架構。
思路:網路請求層唯一的功能就是發送請求,接收響應資料,請求取消,cookie處理這幾個功能,二次助封裝後這些功能可以直接調用封裝好的方法即可。
二次助封裝代碼如下:
1.功能介面:
/********************************************************** * @檔案名稱:DisposeDataListener.java * @檔案rzq * @建立時間:2015年8月19日 上午11:01:13 * @檔案描述: * @修改曆史:2015年8月19日建立初始版本 **********************************************************/public interface DisposeDataListener{ /** * 請求開始回調事件處理 */ public void onStart(); /** * 請求成功回調事件處理 */ public void onSuccess(Object responseObj); /** * 請求失敗回調事件處理 */ public void onFailure(Object reasonObj); /** * 請求重連回調事件處理 */ public void onRetry(int retryNo); /** * 請求進度回調事件處理 */ public void onProgress(long bytesWritten, long totalSize); /** * 請求結束回調事件處理 */ public void onFinish(); /** * 請求取消回調事件處理 */ public void onCancel();}
2.請求功能介面適配器模式
public class DisposeDataHandle implements DisposeDataListener{ @Override public void onStart() { } @Override public void onSuccess(Object responseObj) { } @Override public void onFailure(Object reasonObj) { } @Override public void onRetry(int retryNo) { } @Override public void onProgress(long bytesWritten, long totalSize) { } @Override public void onFinish() { } @Override public void onCancel() { }}
3.請求回調事件處理:
/********************************************************** * @檔案名稱:BaseJsonResponseHandler.java * @檔案rzq * @建立時間:2015年8月19日 上午10:41:46 * @檔案描述:伺服器Response基礎類,包括了java層異常和商務邏輯層異常碼定義 * @修改曆史:2015年8月19日建立初始版本 **********************************************************/public class BaseJsonResponseHandler extends JsonHttpResponseHandler{ /** * the logic layer exception, may alter in different app */ protected final String RESULT_CODE = "ecode"; protected final int RESULT_CODE_VALUE = 0; protected final String ERROR_MSG = "emsg"; protected final String EMPTY_MSG = ""; /** * the java layer exception */ protected final int NETWORK_ERROR = -1; // the network relative error protected final int JSON_ERROR = -2; // the JSON relative error protected final int OTHER_ERROR = -3; // the unknow error /** * interface and the handle class */ protected Class<?> mClass; protected DisposeDataHandle mDataHandle; public BaseJsonResponseHandler(DisposeDataHandle dataHandle, Class<?> clazz) { this.mDataHandle = dataHandle; this.mClass = clazz; } public BaseJsonResponseHandler(DisposeDataHandle dataHandle) { this.mDataHandle = dataHandle; } /** * only handle the success branch(ecode == 0) */ public void onSuccess(JSONObject response) { } /** * handle the java exception and logic exception branch(ecode != 0) */ public void onFailure(Throwable throwObj) { } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { onSuccess(response); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { onFailure(throwable); }}/********************************************************** * @檔案名稱:CommonJsonResponseHandler.java * @檔案rzq * @建立時間:2015年8月19日 上午11:01:13 * @檔案描述:商務邏輯層真正處理的地方,包括java層異常和業務層異常 * @修改曆史:2015年8月19日建立初始版本 **********************************************************/public class CommonJsonResponseHandler extends BaseJsonResponseHandler{ public CommonJsonResponseHandler(DisposeDataHandle dataHandle) { super(dataHandle); } public CommonJsonResponseHandler(DisposeDataHandle dataHandle, Class<?> clazz) { super(dataHandle, clazz); } @Override public void onStart() { mDataHandle.onStart(); } @Override public void onProgress(long bytesWritten, long totalSize) { mDataHandle.onProgress(bytesWritten, totalSize); } @Override public void onSuccess(JSONObject response) { handleResponse(response); } @Override public void onFailure(Throwable throwObj) { mDataHandle.onFailure(new LogicException(NETWORK_ERROR, throwObj.getMessage())); } @Override public void onCancel() { mDataHandle.onCancel(); } @Override public void onRetry(int retryNo) { mDataHandle.onRetry(retryNo); } @Override public void onFinish() { mDataHandle.onFinish(); } /** * handle the server response */ private void handleResponse(JSONObject response) { if (response == null) { mDataHandle.onFailure(new LogicException(NETWORK_ERROR, EMPTY_MSG)); return; } try { if (response.has(RESULT_CODE)) { if (response.optInt(RESULT_CODE) == RESULT_CODE_VALUE) { if (mClass == null) { mDataHandle.onSuccess(response); } else { Object obj = ResponseEntityToModule.parseJsonObjectToModule(response, mClass); if (obj != null) { mDataHandle.onSuccess(obj); } else { mDataHandle.onFailure(new LogicException(JSON_ERROR, EMPTY_MSG)); } } } else { if (response.has(ERROR_MSG)) { mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), response .optString(ERROR_MSG))); } else { mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), EMPTY_MSG)); } } } else { if (response.has(ERROR_MSG)) { mDataHandle.onFailure(new LogicException(OTHER_ERROR, response.optString(ERROR_MSG))); } } } catch (Exception e) { mDataHandle.onFailure(new LogicException(OTHER_ERROR, e.getMessage())); e.printStackTrace(); } }}
4.自訂異常類,對java異常和商務邏輯異常封裝統一處理
/********************************************************** * @檔案名稱:LogicException.java * @檔案rzq * @建立時間:2015年8月19日 上午10:05:08 * @檔案描述:自訂異常類,返回ecode,emsg到業務層 * @修改曆史:2015年8月19日建立初始版本 **********************************************************/public class LogicException extends Exception{private static final long serialVersionUID = 1L;/** * the server return code */private int ecode;/** * the server return error message */private String emsg;public LogicException(int ecode, String emsg){this.ecode = ecode;this.emsg = emsg;}public int getEcode(){return ecode;}public String getEmsg(){return emsg;}} 5.請求發送入口類CommonClient:
/********************************************************** * @檔案名稱:CommonClient.java * @檔案rzq * @建立時間:2015年8月19日 上午11:38:57 * @檔案描述:通用httpclient,支援重連,取消請求,Cookie儲存 * @修改曆史:2015年8月19日建立初始版本 **********************************************************/public class CommonClient{private static AsyncHttpClient client;static{/** * init the retry exception */AsyncHttpClient.allowRetryExceptionClass(IOException.class);AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class);AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class);/** * init the block retry exception */AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class);AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class);client = new AsyncHttpClient();}public static RequestHandle get(String url, AsyncHttpResponseHandler responseHandler){return client.get(url, responseHandler);}public static RequestHandle get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){return client.get(url, params, responseHandler);}public static RequestHandle get(Context context, String url, AsyncHttpResponseHandler responseHandler){return client.get(context, url, responseHandler);}public static RequestHandle get(Context context, String url, RequestParams params,AsyncHttpResponseHandler responseHandler){return client.get(context, url, params, responseHandler);}public static RequestHandle get(Context context, String url, Header[] headers, RequestParams params,AsyncHttpResponseHandler responseHandler){return client.get(context, url, headers, params, responseHandler);}public static RequestHandle post(String url, AsyncHttpResponseHandler responseHandler){return client.post(url, responseHandler);}public static RequestHandle post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){return client.post(url, params, responseHandler);}public static RequestHandle post(Context context, String url, RequestParams params,AsyncHttpResponseHandler responseHandler){return client.post(context, url, params, responseHandler);}public static RequestHandle post(Context context, String url, HttpEntity entity, String contentType,AsyncHttpResponseHandler responseHandler){return client.post(context, url, entity, contentType, responseHandler);}public static RequestHandle post(Context context, String url, Header[] headers, RequestParams params,String contentType, AsyncHttpResponseHandler responseHandler){return client.post(context, url, headers, params, contentType, responseHandler);}public static RequestHandle post(Context context, String url, Header[] headers, HttpEntity entity,String contentType, AsyncHttpResponseHandler responseHandler){return client.post(context, url, headers, entity, contentType, responseHandler);}/** * calcel the context relative request * @param context * @param mayInterruptIfRunning */public void calcelRequests(Context context, boolean mayInterruptIfRunning){client.cancelRequests(context, mayInterruptIfRunning);}/** * cancel current all request in app * @param mayInterruptIfRunning */public void cacelAllrequests(boolean mayInterruptIfRunning){client.cancelAllRequests(mayInterruptIfRunning);}public static void setHttpContextAttribute(String id, Object obj){client.getHttpContext().setAttribute(id, obj);}public static Object getHttpContextAttribute(String id){return client.getHttpContext().getAttribute(id);}public static void removeHttpContextAttribute(String id){client.getHttpContext().removeAttribute(id);}/** * set the cookie store * @param cookieStore */public static void setCookieStore(CookieStore cookieStore){client.setCookieStore(cookieStore);}/** * remove the cookie store */public static void removeCookieStore(){removeHttpContextAttribute(ClientContext.COOKIE_STORE);}}
6.登陸DEMO使用
Cookie的儲存,
public class MyApplicaton extends Application {private static MyApplicaton app;@Overridepublic void onCreate() {super.onCreate();app = this;/** * 為全域 CommonClient添加CookieStore,從PersistentCookieStore中可以拿出所有Cookie */CommonClient.setCookieStore(new PersistentCookieStore(this));}public static MyApplicaton getInstance() {return app;}}
響應體的處理:
private void requestLogin(){RequestParams params = new RequestParams();params.put("mb", "");params.put("pwd", "");CommonClient.post(this, URL, params, new CommonJsonResponseHandler(new DisposeDataHandle(){@Overridepublic void onSuccess(Object responseObj){Log.e("------------->", responseObj.toString());}@Overridepublic void onFailure(Object reasonObj){Log.e("----->", ((LogicException)reasonObj).getEmsg());}@Overridepublic void onProgress(long bytesWritten, long totalSize){Log.e("------------->", bytesWritten + "/" + totalSize);}}));}
經過以上封裝後,基於的http功能都具備了,如果開發中遇到一些特殊的功能,可能再根據具體的需求擴充。
源碼下載
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
android基於開源網路架構asychhttpclient,二次封裝為通用網路請求組件