Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 應用開發:從 Web 伺服器取得並解析 XML 資料

實驗步驟

  1. 配置 J2EE 開發環境,部署 web 應用程式 videoweb 並啟動服務。
  2. 用瀏覽器打開 https://localhost:8080/videoweb/video/list.do 確認 XML 資料能正常輸出。
  3. 建立 Android 客戶端專案,連上同一個位址,把取回的 XML 解析後以清單呈現。

資源檔 res/values/strings.xml

<resources>
    <string name="app_name">視頻資訊客戶端</string>
    <string name="error">網絡連接失敗</string>
</resources>

版面配置

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/title"
        android:layout_width="250dip"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/timelength"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

業務物件 Video

package cn.class3g.domain;

public class Video {
    private Integer id;
    private String title;
    private Integer timelength;

    public Video(Integer id, String title, Integer timelength) {
        super();
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }

    public Video() { }

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public Integer getTimelength() { return timelength; }
    public void setTimelength(Integer timelength) { this.timelength = timelength; }

    public String toString() {
        return "Video [id=" + id + ", title=" + title + ", timelength=" + timelength + "]";
    }
}

業務層 VideoService

package cn.class3g.service;

public class VideoService {

    /**
     * 從伺服器取得最新的視頻資訊
     * @return
     * @throws Throwable
     */
    public static List<Video> getLastVideos() throws Throwable {
        String path =
            "https://192.168.1.102:8080/videoweb/video/list.do";//
            // 實驗環境請填 PC 的 IP,不能用 localhost 或 127.0.0.1
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        return parseXML(inStream);
    }

    private static List<Video> parseXML(InputStream inStream) throws Exception {
        Video video = null;
        List<Video> videos = null;
        XmlPullParser pullParser = Xml.newPullParser();
        pullParser.setInput(inStream, "UTF-8");

        int event = pullParser.getEventType();// 觸發第一個事件

        while (event != XmlPullParser.END_DOCUMENT) {
            switch (event) {
            case XmlPullParser.START_DOCUMENT:
                videos = new ArrayList<Video>();
                break;
            case XmlPullParser.START_TAG:
                if ("video".equals(pullParser.getName())) {
                    int id = new Integer(pullParser.getAttributeValue(0));
                    video = new Video();
                    video.setId(id);
                }
                if (video != null) {
                    if ("title".equals(pullParser.getName())) {
                        video.setTitle(pullParser.nextText());
                    }
                    if ("timelength".equals(pullParser.getName())) {
                        video.setTimelength(new Integer(pullParser.nextText()));
                    }
                }
                break;

            case XmlPullParser.END_TAG:
                if ("video".equals(pullParser.getName())) {
                    videos.add(video);
                    video = null;
                }
                break;
            }
            event = pullParser.next();
        }
        return videos;
    }
}

這裡有個關鍵細節:模擬器或真機要連主機上的服務,位址必須寫 PC 的實際 IP,寫 localhost 只會連到自己。

Activity:MyVideoNewsActivity

public class MyVideoNewsActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            List<Video> videos = VideoService.getLastVideos();// 取得最新視頻資訊
            ListView listView = (ListView) this.findViewById(R.id.listView);
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            for (Video video : videos) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("title", video.getTitle());
                item.put("timelength", "時長:" + video.getTimelength());
                item.put("id", video.getId());
                data.add(item);
            }
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
                    new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
            listView.setAdapter(adapter);
        } catch (Throwable e) {
            Log.e("TAG", e.toString());
            Toast.makeText(this, R.string.error, 1).show();
        }
    }
}

延伸:取得網頁原始碼

版面配置放一顆 Button 與一個 ImageView:

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn_text"
    android:id="@+id/showBtn" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView" />

HtmlService 的寫法是在原本的取圖方法上稍作修改:

public class HtmlService {
    /**
     * 取得指定路徑的 html 程式碼
     * @param path 網頁路徑
     * @return
     * @throws Exception
     */
    public static String getHtml(String path) throws Exception {
        URL url = new URL(path);
        // get // post
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();// 網頁的二進位資料
        outStream.close();
        inStream.close();
        return new String(data, "gb2312");
    }
}
public void onClick(View v) {
    String path = pathText.getText().toString();
    try {
        String htmlcode = HtmlService.getHtml(path);
        resultView.setText(htmlcode);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        Toast.makeText(ShowHtmlActivity.this, R.string.error, 1).show();
    }
}

實作時別忘了在 AndroidManifest.xml 加上網路權限,並且這些網路操作在較新的 Android 版本上必須移出主執行緒,否則會被系統攔下。

Copyright © Linux教程網 All Rights Reserved