Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自己封裝 HTTP 框架:搭配 Service + Thread + Handler 跑非同步任務

編輯:關於 Android 程式設計

本文示範如何把 HTTP 請求抽象成介面、再用 Service 統一調度任務、最後透過 Handler 把結果送回 UI。目標不是重造一個 Apache HttpClient,而是把分層思路走一遍。

一、HTTP 協議的封裝

HTTP 只有 request 與 response 兩個主要角色,封裝結構 accordingly 分成兩組介面:

HttpRequestInter:請求端至少要能拿到底層的 HttpUriRequest、請求的 URL,並提供一個 request() 方法把結果包成 response。

public interface HttpRequestInter {
    HttpUriRequest getHttpRequest();          // 取得底層請求物件
    String getRequestURL();                   // 取得請求的 URL
    HttpResponseInter request() throws Exception;  // 送出請求並取得回應
}

HttpResponseInter:回應端要能提供狀態碼、串流、位元組陣列與字串四種形式的資料。

public interface HttpResponseInter {
    int statusCode();
    InputStream getResponseStream() throws IllegalStateException, IOException;
    byte[] getResponseStreamAsByte() throws IOException;
    String getResponseStreamAsString() throws ParseException, IOException;
}

HttpRequestImpl:同時實作請求介面與 ResponseHandler。ResponseHandler 是 HttpClient 的既有設計,用來把原始 HttpResponse 加工成你要的型別。

public class HttpRequestImpl implements HttpRequestInter, ResponseHandler<HttpResponseInter> {
    protected HttpUriRequest httpUriRequest;
    private AbstractHttpClient abstractHttpClient;

    public HttpRequestImpl(AbstractHttpClient httpClient) {
        this.abstractHttpClient = httpClient;
    }

    public HttpUriRequest getHttpRequest() {
        return httpUriRequest;
    }

    public String getRequestURL() {
        return httpUriRequest.getURI().toString();
    }

    public HttpResponseInter request() throws Exception {
        return abstractHttpClient.execute(httpUriRequest, this);
    }

    @Override
    public HttpResponseInter handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {
        return new HttpResponseImpl(response);
    }
}

HttpResponseImpl:把 HttpResponse 包成統一介面。這裡用 BufferedHttpEntity 包一層,讓 entity 內容可以重複讀取。

public class HttpResponseImpl implements HttpResponseInter {
    private HttpResponse response;
    private HttpEntity entity;

    public HttpResponseImpl(HttpResponse response) throws IOException {
        this.response = response;
        HttpEntity tempEntity = response.getEntity();
        if (null != tempEntity) {
            entity = new BufferedHttpEntity(tempEntity);
        }
    }

    public int statusCode() {
        return response.getStatusLine().getStatusCode();
    }

    public InputStream getResponseStream() throws IllegalStateException, IOException {
        return entity.getContent();
    }

    public String getResponseStreamAsString() throws ParseException, IOException {
        return EntityUtils.toString(entity);
    }

    public byte[] getResponseStreamAsByte() throws IOException {
        return EntityUtils.toByteArray(entity);
    }
}

ExecuteHttpPost:真正組出 POST 請求並掛上參數的地方。

public class ExecuteHttpPost extends HttpRequestImpl {

    public ExecuteHttpPost(AbstractHttpClient httpClient, String url) {
        this(httpClient, url, null);
    }

    public ExecuteHttpPost(AbstractHttpClient httpClient, String url, HttpEntity entity) {
        super(httpClient);
        this.httpUriRequest = new org.apache.http.client.methods.HttpPost(url);
        if (null != entity) {
            ((HttpEntityEnclosingRequestBase) httpUriRequest).setEntity(entity);
        }
    }
}

BaseHttpClient:客戶端門面,負責參數轉換、超時設定與結果型別轉換。

public class BaseHttpClient {
    private AbstractHttpClient httpClient;
    public static final int DEFAULT_RETIES_COUNT = 5;
    protected int retriesCount = DEFAULT_RETIES_COUNT;

    public final static int MAX_TOTAL_CONNECTIONS = 100;
    public final static int WAIT_TIMEOUT = 30000;
    public final static int MAX_ROUTE_CONNECTIONS = 100;
    public final static int CONNECT_TIMEOUT = 10000;
    public final static int READ_TIMEOUT = 10000;

    public BaseHttpClient() {
        initHttpClient();
    }

    private void initHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS);
        ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
                new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS));
        HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager cm =
                new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, httpParams);
        httpClient.setHttpRequestRetryHandler(new BaseHttpRequestRetryHandler(retriesCount));
    }

    /** 把 Map 參數轉成表單需要的 List */
    private List<BasicNameValuePair> parseParams(HashMap<String, Object> params) {
        if (params == null || 0 == params.size()) {
            return null;
        }
        List<BasicNameValuePair> paramsList =
                new ArrayList<BasicNameValuePair>(params.size());
        for (Entry<String, Object> entry : params.entrySet()) {
            paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
        }
        return paramsList;
    }

    public String post(String url) throws Exception {
        return post(url, null);
    }

    public String post(String url, HashMap<String, Object> params) throws Exception {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parseParams(params));
        return request(url, entity).getResponseStreamAsString();
    }

    public <T> T post(String url, HashMap<String, Object> params, Class<T> clz)
            throws Exception {
        return JSONUtil.fromJson(post(url, params), clz);
    }

    public InputStream postAsStream(String url, HashMap<String, Object> params)
            throws Exception {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parseParams(params));
        return request(url, entity).getResponseStream();
    }

    public HttpResponseInter request(String url, HttpEntity entity) throws Exception {
        HttpRequestImpl httpRequestImpl = new ExecuteHttpPost(httpClient, url, entity);
        return httpRequestImpl.request();
    }
}

BaseHttpRequestRetryHandler:用白名單/黑名單決定哪些例外值得重試。

public class BaseHttpRequestRetryHandler implements HttpRequestRetryHandler {
    private int max_retry_count;

    public BaseHttpRequestRetryHandler(int maxretryCount) {
        this.max_retry_count = maxretryCount;
    }

    private static HashSet<Class<? extends IOException>> exceptionWhiteList =
            new HashSet<Class<? extends IOException>>();
    private static HashSet<Class<? extends IOException>> exceptionBlackList =
            new HashSet<Class<? extends IOException>>();

    static {
        // 這些通常是偶發問題,值得重試
        exceptionWhiteList.add(NoHttpResponseException.class);
        exceptionWhiteList.add(UnknownHostException.class);
        exceptionWhiteList.add(SocketException.class);
        // 這些重試也沒用
        exceptionBlackList.add(SSLException.class);
        exceptionBlackList.add(InterruptedIOException.class);
        exceptionBlackList.add(SocketTimeoutException.class);
    }

    public boolean retryRequest(IOException exception, int executionCount,
                                HttpContext context) {
        if (executionCount > max_retry_count) return false;
        if (exceptionBlackList.contains(exception.getClass())) return false;
        if (exceptionWhiteList.contains(exception.getClass())) return true;

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
        if (!idempotent) return true;   // 非冪等請求,重送前要三思

        Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
        boolean sent = (b != null && b.booleanValue());
        return !sent;
    }
}

二、Service 與非同步任務的結合

整體思路:所有任務統一丟給 Service 排隊,Service 內部開一條線程輪詢佇列,任務完成後透過 Handler 通知對應的 Activity 刷新介面。

任務實體 Task:用 taskId 區分任務類型,taskParams 攜帶參數。

public class Task {
    private int taskId;
    private Map<String, Object> taskParams;
    public static final int USER_LOGIN = 1;

    public Task(int taskId, Map<String, Object> taskParams) {
        this.taskId = taskId;
        this.taskParams = taskParams;
    }

    public int getTaskId() { return taskId; }
    public Map<String, Object> getTaskParams() { return taskParams; }
}

MainService:任務佇列 + 工作線程 + Handler 回呼 + Activity 註冊表。

public class MainService extends Service implements Runnable {
    private static Queue<Task> tasks = new LinkedList<Task>();
    private static ArrayList<Activity> appActivities = new ArrayList<Activity>();
    private boolean isRun;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Task.USER_LOGIN:
                    MainActivityInter activity =
                            (MainActivityInter) getActivityByName("MainActivity");
                    activity.refresh(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    /** 對外暴露:新增一個任務 */
    public static void newTask(Task t) {
        tasks.add(t);
    }

    @Override
    public void onCreate() {
        isRun = true;
        new Thread(this).start();
        super.onCreate();
    }

    /** 線程主體:不停撈取佇列中的任務 */
    public void run() {
        while (isRun) {
            if (!tasks.isEmpty()) {
                Task task = tasks.poll();
                if (null != task) {
                    doTask(task);
                }
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // ignore
            }
        }
    }

    private void doTask(Task task) {
        Message msg = handler.obtainMessage();
        msg.what = task.getTaskId();
        switch (task.getTaskId()) {
            case Task.USER_LOGIN:
                HashMap<String, Object> paramsHashMap =
                        (HashMap<String, Object>) task.getTaskParams();
                String url = "https://172.23.252.89:8080/igouServ/userlogin.action";
                BaseHttpClient httpClient = new BaseHttpClient();
                try {
                    msg.obj = httpClient.post(url, paramsHashMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        handler.sendMessage(msg);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /** 把 Activity 登記進來,Service 才能回頭操作 UI */
    public static void addActivity(Activity activity) {
        appActivities.add(activity);
    }

    private Activity getActivityByName(String name) {
        for (Activity activity : appActivities) {
            if (null != activity
                    && activity.getClass().getName().indexOf(name) > 0) {
                return activity;
            }
        }
        return null;
    }

    /** 一鍵退出:關掉所有 Activity 並停掉自己 */
    public static void appExit(Context context) {
        for (Activity activity : appActivities) {
            if (!activity.isFinishing()) activity.finish();
        }
        context.stopService(new Intent(context, MainService.class));
    }
}

MainActivityInter:讓 Service 有辦法反過來刷新介面。

public interface MainActivityInter {
    void init();
    void refresh(Object... params);
}

三、Activity 端怎麼用

public class MainActivity extends Activity implements MainActivityInter {
    private Button btn_login;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_login = (Button) findViewById(R.id.btn_login);
        textView = (TextView) findViewById(R.id.textView1);

        startService(new Intent(this, MainService.class));  // 啟動服務
        MainService.addActivity(this);                      // 把自己登記進去

        btn_login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Map<String, Object> paramsHashMap = new HashMap<String, Object>(2);
                paramsHashMap.put("userName", "xuliugen");
                paramsHashMap.put("password", "123456");
                MainService.newTask(new Task(Task.USER_LOGIN, paramsHashMap));
            }
        });
    }

    public void init() { }

    public void refresh(Object... params) {
        textView.setText(params[0].toString());
    }
}

這套設計的問題在哪裡

能跑,但用今天的標準看有幾個明顯缺陷,值得一併記住:

  • Apache HttpClient 早已在 Android 5.0 被移除,新專案請改用 HttpURLConnection、OkHttp 或 Retrofit。
  • Service 持有 Activity 參照是記憶體洩漏的標準寫法。Activity 銷毀後若沒從 appActivities 移除,畫面已經關掉卻還被 Service 抓住。正確做法是用 WeakReference、改用 ViewModel/LiveData,或直接讓 Service 只負責資料層。
  • 輪詢佇列 + Thread.sleep(1000) 是浪費資源的設計,用 BlockingQueue 的 take() 阻塞等待即可,不必空轉。
  • Service 預設跑在主線程,網路請求一定要在自己的線程上,這一點範例做對了,但要注意 Handler 相關操作仍然回到主線程。
  • 長時間下載/上傳應該用前景服務並顯示通知,Android 8.0 之後背景服務限制嚴格,否則工作會被系統隨手掐掉。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved