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

Android 訪問 Web 專案並解析其返回的 XML 檔案

編輯:關於 Android 程式設計

本文要示範的是:如何讓 Android 客戶端訪問一個 Web 專案,並解析伺服器返回的 XML 檔案。整個流程可分為「伺服器端建置」與「Android 客戶端解析」兩大部分。

一、建立 Web 伺服器端

首先建立一個簡單的 Web 專案,採用 Servlet 技術。以下是 Servlet 的實作,它會取得最新資訊清單並轉發到 JSP 頁面:

package com.yehui.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yehui.service.VideoNewsService;
import com.yehui.service.bean.News;
import com.yehui.service.impl.VideoNewsServiceImpl;

public class ListServlet extends HttpServlet {
    private VideoNewsService service = new VideoNewsServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<News> videos = service.getLastNews();
        request.setAttribute("videos", videos);
        // 括號裡是 JSP 檔案的路徑
        request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
    }
}

Service 操作的資料物件 News:

package com.yehui.service.bean;

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

    public News() {
    }

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

    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;
    }
}

Service 介面與實作:

// VideoNewsService.java
package com.yehui.service;

import java.util.List;
import com.yehui.service.bean.News;

public interface VideoNewsService {
    // 獲取最新的資訊
    public List<News> getLastNews();
}

// VideoNewsServiceImpl.java
package com.yehui.service.impl;

import java.util.ArrayList;
import java.util.List;
import com.yehui.service.VideoNewsService;
import com.yehui.service.bean.News;

public class VideoNewsServiceImpl implements VideoNewsService {
    public List<News> getLastNews() {
        List<News> newes = new ArrayList<News>();
        newes.add(new News(1, "喜洋洋", 90));
        newes.add(new News(2, "灰太狼", 30));
        newes.add(new News(3, "範例資料", 10));
        return newes;
    }
}

JSP 檔案的重點在於要返回 XML 結果,因此第一行必須加上 XML 宣告:

<%@ page language="java" contentType="text/xml; charset=UTF-8" import="java.util.*" pageEncoding="utf-8"%><?xml version="1.0" encoding="UTF-8"?>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<videonews >
    <c:forEach items="${videos}" var="video" >
    <news id="${video.id}">
    <title>${video.title}</title>
    <timelength>${video.timelength}</timelength>
    </news>
    </c:forEach>
</videonews>

最後在 web.xml 中配置 Servlet 的對應關係:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
    https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>ListServlet</servlet-name>
        <servlet-class>com.yehui.servlet.ListServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ListServlet</servlet-name>
        <url-pattern>/ListServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

至此,Web 伺服器端便建置完成。接下來說明 Android 客戶端。

二、Android 客戶端

客戶端同樣需要一個對應的資料物件 News(結構與伺服器端一致),此處省略重複的 getter/setter。

Service 部分透過 Pull 技術解析伺服器返回的 XML:

package com.yehui.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;

import com.yehui.bean.News;

public class VideoNewsService {
    public static List<News> getLastNews() throws Exception {
        List<News> newes = new ArrayList<News>();
        URL url = new URL("https://169.254.161.54:8888/web/ListServlet");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.connect();
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            // 頁面返回值為 XML 檔案,使用 pull 解析器進行解析
            newes = parseXML(inputStream);
        }
        return newes;
    }

    // pull 解析伺服器返回的 XML 檔案
    private static List<News> parseXML(InputStream inputStream) throws Exception {
        XmlPullParser xmlPullParser = Xml.newPullParser();
        xmlPullParser.setInput(inputStream, "utf-8");
        int event = xmlPullParser.getEventType();
        List<News> newes = new ArrayList<News>();
        News news = null;
        while (event != xmlPullParser.END_DOCUMENT) {
            switch (event) {
                case 2:
                    if ("news".equals(xmlPullParser.getName())) {
                        int id = Integer.valueOf(xmlPullParser.getAttributeValue(0));
                        news = new News();
                        news.setId(id);
                    } else if ("title".equals(xmlPullParser.getName())) {
                        news.setTitle(xmlPullParser.nextText());
                    } else if ("timelength".equals(xmlPullParser.getName())) {
                        news.setTimelength(Integer.valueOf(xmlPullParser.nextText()));
                    }
                    break;
                case 3:
                    if ("news".equals(xmlPullParser.getName())) {
                        newes.add(news);
                        news = null;
                    }
                    break;
                default:
                    break;
            }
            event = xmlPullParser.next();
        }
        return newes;
    }
}

在 Activity 中開一條執行緒呼叫 Service,透過 Handler 把資料回傳主執行緒並更新 UI:

package com.yehui.news;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.yehui.bean.News;
import com.yehui.service.VideoNewsService;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView listview;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            try {
                List<News> newes = (List<News>) msg.obj;
                List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                for (News news : newes) {
                    HashMap<String, Object> item = new HashMap<String, Object>();
                    item.put("title", news.getTitle());
                    item.put("timelength", news.getTimelength());
                    data.add(item);
                }
                SimpleAdapter simpleAdapter = new SimpleAdapter(
                        getApplicationContext(), data, R.layout.item,
                        new String[] { "title", "timelength" }, new int[] {
                        R.id.title, R.id.timelength });
                listview.setAdapter(simpleAdapter);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), R.string.error, 1).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview = (ListView) this.findViewById(R.id.listview);
        new Thread() {
            @Override
            public void run() {
                List<News> newes;
                try {
                    newes = VideoNewsService.getLastNews();
                    Message msg = new Message();
                    msg.obj = newes;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

ListView 的版面配置與行配置檔如下:

<!-- listview 版面 -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

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

</LinearLayout>

<!-- listview 的行版面 -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

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

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

</LinearLayout>

最後別忘了在清單檔中加入網路訪問權限,否則程式會因缺少權限而無法連線:

<uses-permission android:name="android.permission.INTERNET"/>

整體來說,這套流程就是:Web 端用 Servlet 產生 XML、Android 端用 HttpURLConnection 抓取後以 Pull 解析器拆解,再透過 Handler 更新 ListView。掌握這條主線,就能延伸出各種客戶端與伺服器互動的應用。

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