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

Android 開發之網路請求:HttpURLConnection 詳解

編輯:Android 程式設計入門

Android 主要提供了兩種方式來進行 HTTP 操作:HttpURLConnection 和 HttpClient。這兩者都支援 HTTPS 協議、以串流形式進行上傳下載、設定逾時時間、IPv6 以及連線池等功能。

HttpClient

DefaultHttpClient 和它的兄弟 AndroidHttpClient 都是 HttpClient 的具體實作類,它們擁有大量 API,而且運行穩定、bug 也很少。但也正因為 API 數量過多,導致很難在不破壞相容性的前提下對它進行升級擴展,所以目前 Android 團隊在優化 HttpClient 這方面的態度並不積極。

HttpURLConnection

HttpURLConnection 是一個多用途、極輕量的 HTTP 用戶端,用它來做 HTTP 操作可以適用於大多數的應用場景。雖然它提供的 API 比較簡單,但也正因如此,我們能更輕鬆地使用與擴展它。

哪一種才是最好的選擇?

在 Android 2.2 版本之前,HttpClient 的 bug 較少,因此是比較好的選擇;而在 Android 2.3 版本及以後,HttpURLConnection 才是最佳選擇。它 API 簡單、體積小,非常適合 Android 專案,加上壓縮與快取機制能有效減少網路流量,在提速與省電方面都發揮了不小的作用。因此新的應用程式應該更傾向於採用 HttpURLConnection。

HttpURLConnection 程式碼:

 private void checkVersion() { final long startTime = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { Message msg = mHandler.obtainMessage(); HttpURLConnection conn = null; try { URL url = new URL("https://10.0.2.2:8080/update.json"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //請求方法為GET conn.setConnectTimeout(5000); //鏈接超時為5秒 conn.setReadTimeout(5000); //讀取超時為5秒 conn.connect(); int responseCode = conn.getResponseCode(); if ( responseCode == 200 ) { InputStream inputStream = conn.getInputStream(); String result = StreamUtils.readFromStream(inputStream); VersionBean versionBean = parseJsonWithGson(result); mVersionName = versionBean.getVersionName(); mDescription = versionBean.getDescription(); mVersionCode = versionBean.getVersionCode(); mDownLoadUrl = versionBean.getDownLoadUrl(); LogUtils.e(TAG, mDownLoadUrl); if ( mVersionCode > getAppVersionCode() ) { msg.what = CODE_UPDATE_INFO; } else { msg.what = CODE_GO_HOME; } } } catch ( MalformedURLException e ) { msg.what = CODE_URL_ERROR; e.printStackTrace(); } catch ( IOException e ) { msg.what = CODE_NETWORK_ERROR; e.printStackTrace(); } finally { long endTime = System.currentTimeMillis(); long timeUsed = endTime - startTime; if ( timeUsed < 2000 ) { try { Thread.sleep(2000 - timeUsed); } catch ( InterruptedException e ) { e.printStackTrace(); } } mHandler.sendMessage(msg); if ( conn != null ) { conn.disconnect(); } } } }).start(); }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved