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

Android 網絡通信的兩種基本实现:HttpClient 與 HttpURLConnection 對比封裝

編輯:關於 Android 程式設計

隔了一段時間沒寫博客,翻出去年上半年寫的代碼看,設計上確實有不少局限,但基本的通信流程已經跑通了。不知道以後回看現在寫的東西,是不是也會有同樣的感慨。

Android 上實現網絡通信,主流就兩條路:HttpClient 和 HttpURLConnection。下面把兩種實現都封裝一遍,順便做個對比。

一、先抽一層抽象基類

把公共的常量、超時配置、請求方式枚舉和抽象方法集中到 AbstractHttp 裡,兩種實現各自繼承即可。

public abstract class AbstractHttp {

    /** 默認編碼 */
    public static final String DEFAULT_ENCODING = "UTF-8";
    /** GET 請求時 url 與參數的分隔符 */
    public static final String URL_AND_PARA_SEPARATOR = "?";
    /** 是否取消請求 */
    protected boolean isCancel = false;
    public static final int DEFAULT_BYTE_LENGTH = 8192;

    protected static final int LONG_TIME = 0;
    protected int connectionTimeOut = LONG_TIME;
    protected int soTimeOut = LONG_TIME;

    public enum HttpMethod { GET, POST }

    public AbstractHttp() { super(); }

    public AbstractHttp(int connectionTimeOut, int soTimeOut) {
        super();
        if (connectionTimeOut < 0 || soTimeOut < 0) {
            throw new RuntimeException("connectionTimeOut<0 || soTimeOut<0");
        }
        if (connectionTimeOut > 0) this.connectionTimeOut = connectionTimeOut;
        if (soTimeOut > 0) this.soTimeOut = soTimeOut;
    }

    /** 取消請求 */
    protected void cancel() { isCancel = true; }

    /** 異步線程 */
    protected void asyncThread(Runnable runnable) { new Thread(runnable).start(); }

    /** 異步連接,默認 GET */
    public abstract void asyncConnect(String url, HttpCallBack<String> httpCallBack);
    public abstract void asyncConnect(String url, Map<String, String> params, HttpCallBack<String> httpCallBack);
    public abstract void asyncConnect(String url, Map<String, String> params, HttpMethod httpMethod, HttpCallBack<String> httpCallBack);

    /** 同步連接 */
    public abstract String syncConnect(String url);
    public abstract String syncConnect(String url, Map<String, String> params);
    public abstract String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod);
    public abstract String syncConnect(String url, Map<String, String> params, HttpCallBack<String> httpCallBack);
    public abstract String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod, HttpCallBack<String> httpCallBack);

    /** 下載文件 */
    public abstract void asyncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack);
    public abstract File syncDownloadFile(String url, String fileName);
    public abstract File syncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack);
}

二、回調接口設計

回調覆蓋了請求生命週期中的所有節點:開始、加載進度、成功、失敗、取消。

public interface HttpCallBack<T> {
    void onStart(String url);
    void onLoading(long progress, long count);
    void onSuccess(T t);
    void onFailure(String error, Throwable e);
    void onCancel();
}

再派生出兩個特化版本,讓業務方不用關心泛型細節:

public abstract class HttpConnectCallBack implements HttpCallBack<String> {
    @Override public abstract void onSuccess(String content);
}

public abstract class HttpDownloadCallBack implements HttpCallBack<File> {
    @Override public abstract void onSuccess(File file);
}

三、HttpClient 實現

關鍵點在 getHttpClient():通過 SchemeRegistry 同時註冊 http 與 https,並用 ThreadSafeClientConnManager 支持線程安全的連接池;請求對象的構造交給 getHttpUriRequest(),POST 時把 Map 轉成 UrlEncodedFormEntity,GET 時則用 URLEncodedUtils 把參數拼到 URL 後面。

public class Http extends AbstractHttp {

    public Http() { super(); }
    public Http(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); }

    private HttpClient getHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        if (connectionTimeOut != LONG_TIME && soTimeOut != LONG_TIME) {
            HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeOut);
            HttpConnectionParams.setSoTimeout(httpParams, soTimeOut);
        }
        HttpConnectionParams.setTcpNoDelay(httpParams, true);
        HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_BYTE_LENGTH);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        return new DefaultHttpClient(manager, httpParams);
    }

    private HttpUriRequest getHttpUriRequest(String url, HttpMethod httpMethod, Map<String, String> params) {
        if (HttpMethod.POST == httpMethod) {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                for (String key : params.keySet()) {
                    list.add(new BasicNameValuePair(key, params.get(key)));
                }
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(list, DEFAULT_ENCODING));
                } catch (UnsupportedEncodingException e) { }
            }
            return httpPost;
        } else {
            if (params != null) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                for (String key : params.keySet()) {
                    list.add(new BasicNameValuePair(key, params.get(key)));
                }
                url += URL_AND_PARA_SEPARATOR;
                url += URLEncodedUtils.format(list, DEFAULT_ENCODING);
            }
            return new HttpGet(url);
        }
    }

    @Override
    public void asyncConnect(final String url, final Map<String, String> params,
                             final HttpMethod httpMethod, final HttpCallBack<String> httpCallBack) {
        asyncThread(new Runnable() {
            @Override public void run() {
                syncConnect(url, params, httpMethod, httpCallBack);
            }
        });
    }

    @Override
    public String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod,
                              HttpCallBack<String> httpCallBack) {
        if (TextUtils.isEmpty(url)) return null;

        BufferedReader reader = null;
        HttpClient httpClient = null;
        int statusCode = -1;
        try {
            if (httpCallBack != null) httpCallBack.onStart(url);
            HttpUriRequest request = getHttpUriRequest(url, httpMethod, params);
            httpClient = getHttpClient();
            HttpResponse httpResponse = httpClient.execute(request);
            statusCode = httpResponse.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
                StringBuffer buffer = new StringBuffer();
                String line = null;
                long progress = 0;
                long count = httpResponse.getEntity().getContentLength();
                isCancel = false;
                if (httpCallBack != null && count != -1) httpCallBack.onLoading(progress, count);

                while ((!isCancel) && (line = reader.readLine()) != null) {
                    buffer.append(line);
                    if (httpCallBack != null && count != -1) {
                        progress += line.getBytes().length;
                        httpCallBack.onLoading(progress, count);
                    }
                }

                if (httpCallBack != null) {
                    if (!isCancel) {
                        httpCallBack.onLoading(count, count);
                    } else {
                        reader.close();
                        httpCallBack.onCancel();
                        return null;
                    }
                }
                reader.close();
                if (httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString());
                return buffer.toString();
            } else {
                if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null);
            }
        } catch (Exception e) {
            if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e);
        } finally {
            if (httpClient != null) httpClient.getConnectionManager().shutdown();
        }
        return null;
    }

    @Override
    public File syncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack) {
        // 與 syncConnect 結構一致,差別在於把響應流寫入 FileOutputStream,
        // 並用 1 秒的時間閾值控制 onLoading 的回調頻率,避免刷新過於頻繁
        return null;
    }
}

異步方法只是把同步邏輯包一層線程,同步方法才是真正幹活的地方,這樣設計的好處是同一套核心邏輯能同時支持兩種調用方式。下載文件時,進度回調做了節流處理:每累積 1 秒才回報一次,避免頻繁觸發 UI 刷新。

四、HttpURLConnection 實現

接口完全一致,只是內部換成 JDK 原生的連接類。核心在 getHttpURLConnection():GET 把參數拼到 URL,POST 則設置 doOutput 並寫入輸出流。

public class KingHttp extends AbstractHttp {

    public KingHttp() { super(); }
    public KingHttp(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); }

    private HttpURLConnection getHttpURLConnection(String url, HttpMethod httpMethod,
                                                   Map<String, String> params) throws IOException {
        String paras = null;
        if (params != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            paras = URLEncodedUtils.format(list, DEFAULT_ENCODING);
        }
        if (HttpMethod.GET == httpMethod && paras != null) {
            url += URL_AND_PARA_SEPARATOR;
            url += paras;
        }

        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        httpURLConnection.setConnectTimeout(connectionTimeOut);
        httpURLConnection.setReadTimeout(soTimeOut);
        httpURLConnection.setUseCaches(false);

        if (HttpMethod.POST == httpMethod) {
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            if (paras != null) httpURLConnection.getOutputStream().write(paras.getBytes());
        } else {
            httpURLConnection.setRequestMethod("GET");
        }
        return httpURLConnection;
    }

    @Override
    public String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod,
                              HttpCallBack<String> httpCallBack) {
        if (TextUtils.isEmpty(url)) return null;

        BufferedReader reader = null;
        HttpURLConnection conn = null;
        int statusCode = -1;
        try {
            if (httpCallBack != null) httpCallBack.onStart(url);
            conn = getHttpURLConnection(url, httpMethod, params);
            conn.connect();
            statusCode = conn.getResponseCode();

            if (statusCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer buffer = new StringBuffer();
                String line = null;
                long progress = 0;
                long count = conn.getContentLength();
                isCancel = false;

                while ((!isCancel) && (line = reader.readLine()) != null) {
                    buffer.append(line);
                    if (httpCallBack != null && count != -1) {
                        progress += line.getBytes().length;
                        httpCallBack.onLoading(progress, count);
                    }
                }
                reader.close();
                if (httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString());
                return buffer.toString();
            } else {
                if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null);
            }
        } catch (Exception e) {
            if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e);
        } finally {
            if (conn != null) conn.disconnect();
        }
        return null;
    }
}

五、兩者該怎麼選

HttpClient 的優勢是 API 完備、連接池管理成熟,適合需要大量並發請求、需要精細控制連接行為的場景;缺點是它已被 Google 標記為不再維護,Android 6.0 之後需要自行引入 jar 包。

HttpURLConnection 是官方推薦的方案,在 Android 上做了針對性的優化(例如與內建的 HTTP 連接池、響應緩存配合更好),代碼也更精簡。新項目直接用它即可。

無論選哪種,封裝思路是一致的:抽象基類定接口 → 具體實現換内核 → 回調接口對外暴露結果,這樣上層業務完全不依賴具體的網絡庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved