android基於開源網絡框架asychhttpclient,二次封裝為通用網絡請求組件
網絡請求是全部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; @Override public 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() { @Override public void onSuccess(Object responseObj) { Log.e("------------->", responseObj.toString()); } @Override public void onFailure(Object reasonObj) { Log.e("----->", ((LogicException)reasonObj).getEmsg()); } @Override public void onProgress(long bytesWritten, long totalSize) { Log.e("------------->", bytesWritten + "/" + totalSize); } })); }
經過以上封裝後。基於的http功能都具備了,假設開發中遇到一些特殊的功能,可能再依據詳細的需求擴展。
源代碼下載
android基於開源網絡框架asychhttpclient,二次封裝為通用網絡請求組件