在Android中,可以有多種方式來實作網絡程式設計:
建立URL,并使用URLConnection/HttpURLConnection
使用HttpClient
使用WebView
建立URL,并使用URLConnection/HttpURLConnection
java.net.*下面提供了通路 HTTP 服務的基本功能。使用這部分接口的基本操作主要包括:
建立 URL 以及 URLConnection / HttpURLConnection 對象
1 設定連接配接參數
2 連接配接到伺服器
3 向伺服器寫資料
4 從伺服器讀取資料
源碼:
- try {
- // 建立URL對象
- URL url = new URL("http://t.sina.cn/fesky");
- // 建立URL連接配接
- URLConnection connection = url.openConnection();
- // 對于 HTTP 連接配接可以直接轉換成 HttpURLConnection,
- // 這樣就可以使用一些 HTTP 連接配接特定的方法,如 setRequestMethod() 等
- // HttpURLConnection connection
- // =(HttpURLConnection)url.openConnection(Proxy_yours);
- // 設定參數
- connection.setConnectTimeout(10000);
- connection.addRequestProperty("User-Agent", "J2me/MIDP2.0");
- // 連接配接伺服器
- connection.connect();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
使用HttpClient
對于HttpClient類,可以使用HttpPost和HttpGet類以及HttpResponse來進行網絡連接配接。
使用WebView
Android手機中内置了一款高性能webkit核心浏覽器,在SDK中封裝成了WebView元件。
http://developer.android.com/guide/tutorials/views/hello-webview.html提供了一個簡單的例子:
1. webview的XML定義:
- <WebView
- android:id="@+id/webview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- />
2.Manifest檔案中權限的設定:
- <uses-permission android:name="android.permission.INTERNET" />
3.如果想要支援JavaScript:
- webview.getSettings().setJavaScriptEnabled(true);
4.如果需要在WebView中顯示網頁,而不是在内置浏覽器中浏覽,則需要mWebView.setWebViewClient,并重寫shouldOverrideUrlLoading方法。
5.如果不做任何處理,在顯示你的Brower UI時,點選系統“Back”鍵,整個Browser會作為一個整體“Back"到其他Activity中,而不是希望的在Browser的曆史頁面中Back。如果希望實作在曆史頁面中Back,需要在目前Activity中處理Back事件:mWebView.goBack();
- WebView webview;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 擷取WebView對象
- webview = (WebView) findViewById(R.id.webview);
- // 使能JavaScript
- webview.getSettings().setJavaScriptEnabled(true);
- // 如果需要在WebView中顯示網頁,而不是在内置浏覽器中浏覽,
- // 則需要mWebView.setWebViewClient,并重寫
- // shouldOverrideUrlLoading方法。
- webview.setWebViewClient(new WebViewClientDemo());
- // 加載網頁
- webview.loadUrl("http://t.sina.cn/fesky");
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // 按下BACK鍵回到曆史頁面中
- if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
- webview.goBack();
- return true;
- }
- return super.onKeyDown(keyCode, event);
- }
- private class WebViewClientDemo extends WebViewClient {
- @Override
- // 在WebView中而不是預設浏覽器中顯示頁面
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- }
- webview.loadData(html, “text/html”, "utf-8”); 如果html中包含中文,則需要webview.loadData(URLEncoder.encode(html,encoding), mimeType, encoding); 對于本地圖檔或網頁的顯示,可以使用loadUrl,不過Url的位址字首為file:///,如"file:///android_asset/test.htm”。