編輯:關於 Android 程式設計
網絡請求是所有 App 必不可少的功能。如果每次開發都重寫一遍網絡請求,或者把舊代碼復制到新項目,顯然不夠合理。出於這一考慮,我把整個網絡請求層獨立出來,與業務邏輯分離,這樣就能避免每次重複編寫。本文基於較為熟悉的 asynchttpclient 進行二次封裝。
思路:網絡請求層的唯一職責就是發送請求、接收響應、取消請求與處理 Cookie。二次封裝後,這些功能都能通過調用封裝好的方法直接完成。
1. 功能接口
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 層異常與業務邏輯層異常碼的定義;CommonJsonResponseHandler 則是真正處理業務的地方,負責解析服務器返回並判斷 ecode:
public class BaseJsonResponseHandler extends JsonHttpResponseHandler {
// 業務邏輯層異常,可在不同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 = "";
// Java層異常
protected final int NETWORK_ERROR = -1; // 網絡相關錯誤
protected final int JSON_ERROR = -2; // JSON相關錯誤
protected final int OTHER_ERROR = -3; // 未知錯誤
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;
}
public void onSuccess(JSONObject response) { }
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);
}
}
4. 自定義異常類
把 Java 異常與業務邏輯異常統一封裝,返回 ecode、emsg 給業務層:
public class LogicException extends Exception {
private static final long serialVersionUID = 1L;
private int ecode; // 服務器返回碼
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
統一封裝 get、post 方法,支持重連、取消請求與 Cookie 存儲:
public class CommonClient {
private static AsyncHttpClient client;
static {
// 允許重試的異常
AsyncHttpClient.allowRetryExceptionClass(IOException.class);
AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class);
AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class);
// 禁止重試的異常
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 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);
}
/** 取消指定context相關的請求 */
public void calcelRequests(Context context, boolean mayInterruptIfRunning) {
client.cancelRequests(context, mayInterruptIfRunning);
}
/** 取消app中所有請求 */
public void cacelAllrequests(boolean mayInterruptIfRunning) {
client.cancelAllRequests(mayInterruptIfRunning);
}
/** 設置Cookie存儲 */
public static void setCookieStore(CookieStore cookieStore) {
client.setCookieStore(cookieStore);
}
}
6. 登錄 DEMO 使用
在 Application 中為全局 CommonClient 添加 CookieStore,即可自動保存登錄狀態:
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 學習筆記 038:WebView 網頁視圖完全指南
前面我們介紹過 HTTP 協議和 Socket,這一篇我們來聊聊 Android 的一個網絡控件——WebView 網頁視圖。眾所周知,目前移動端有兩種開發方向:原生開發
Android ListView 效能優化的幾種常見寫法
ListView 的基本原理ListView 是 Android 中常用的垂直捲動列表。它通常透過 Adapter 將資料轉換成畫面項目,而 getView 方法就是產生
Android 應用簽名完整指南:Eclipse 操作與命令列實作
簽名的作用 Android 應用以套件名稱作為唯一識別。若兩個應用程式使用相同套件名稱,後安裝者可能覆蓋先安裝者。為了避免這種情況,Android 要求正式發布的應用必須
Android 項目實戰:完整拆解天氣預報應用的實現過程
需求很直白:輸入城市名,點擊查詢,列表依次展示未來七天的天氣,並帶有入場動畫。 一、搞定數據來源 提供天氣服務的網站不少,通常都會開放 API 供開發者調用。這裡以聚