Android入門:通過XML數據與服務器進行通信

一、與服務器通信

類似於瀏覽器與服務器通信,Android應用也可以與Web服務器通信,比如Android應用可以訪問Servlet、JSP、圖片等等;
Web服務器通過指定Content-Type可以指定返回的數據的類型,比如text/html表示網頁,text/xml表示XML數據,image/jpeg為圖片;

二、通過XML讓客戶端和服務器交流數據

 

比如Android客戶端打開相親網,則返回的是多個人的序列,包含人的姓名、年齡等信息,而怎麼組織這些數據返回給客戶端呢?用XML很方便;

 

三、代碼實現

服務器使用瞭dom4j組織XML數據,並返回給客戶端;

代碼結構如下:

 

 

[java]
package org.xiazdong.servlet; 
 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import org.dom4j.Document; 
import org.dom4j.DocumentHelper; 
import org.dom4j.Element; 
import org.xiazdong.domain.Person; 
 
 
@WebServlet("/ListServlet") 
public class ListServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doPost(request,response); 
    } 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        List<Person> list = new ArrayList<Person>(); 
        for(int i=0;i<4;i++){ 
            Person person = new Person(i,"xiazdong-"+i,20+i); 
            list.add(person); 
        } 
        Document document = DocumentHelper.createDocument(); 
        Element persons = DocumentHelper.createElement("persons"); 
        document.add(persons); 
        for(int i=0;i<4;i++){ 
            persons.addElement("person").addAttribute("id", list.get(i).getId()+""); 
            persons.addElement("name").addText(list.get(i).getName()); 
            persons.addElement("age").addText(list.get(i).getAge()+""); 
        } 
        String xml = document.asXML();  //用dom4j組織一個XML字符串 
        response.setContentType("text/xml; charset=UTF-8"); //設置返回值的類型 
        response.getOutputStream().write(xml.getBytes("UTF-8"));    //設置返回值 
    } 
 

如果讓瀏覽器訪問,效果如下:

(註:Chrome打開總是顯示不出XML聲明。請用IE打開)


接下來,我們可以開發客戶端,目標是用列表顯示這些數據;

在AndroidManifest.xml中加入:

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

每個item的佈局如下:

[html] 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" > 
 
    <TextView 
        android:layout_width="50dp" 
        android:layout_height="wrap_content"  
        android:id="@+id/id" 
        /> 
    <TextView 
        android:layout_width="100dp" 
        android:layout_height="wrap_content"  
        android:id="@+id/name" 
        /><TextView 
        android:layout_width="50dp" 
        android:layout_height="wrap_content"  
        android:id="@+id/age" 
        /> 
 
</LinearLayout> 

 

MainActivity.java

[java] 
package org.xiazdong.personlist; 
 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import org.xiazdong.domain.Person; 
import org.xmlpull.v1.XmlPullParser; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.util.Xml; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
 
public class MainActivity extends Activity { 
    private ListView listView; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        listView = (ListView) this.findViewById(R.id.listview); 
        List<Person> persons = null; 
        try { 
            persons = getXMLData(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>(); 
        for (Person person : persons) { 
            HashMap<String, Object> map = new HashMap<String, Object>(); 
            map.put("id", person.getId()); 
            map.put("name", person.getName()); 
            map.put("age", person.getAge()); 
            maps.add(map); 
        } 
        SimpleAdapter adapter = new SimpleAdapter(this, maps, R.layout.item, 
                new String[] { "id", "name", "age" }, new int[] { R.id.id, 
                        R.id.name, R.id.age }); 
        listView.setAdapter(adapter); 
    } 
 
    //讀取XML數據並轉為List<Person> 
    private List<Person> getXMLData() throws Exception { 
        List<Person> persons = new ArrayList<Person>(); 
        Person person = null; 
        URL url = new URL("http://192.168.0.103:8080/Server/ListServlet"); 
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
        conn.setRequestMethod("GET"); 
        if (conn.getResponseCode() == 200) { 
            InputStream in = conn.getInputStream(); 
            XmlPullParser parser = Xml.newPullParser(); 
            parser.setInput(in, "UTF-8"); 
            int event = parser.getEventType(); 
            while (event != XmlPullParser.END_DOCUMENT) { 
                Log.i("start_document", "start_document"); 
                switch (event) { 
                case XmlPullParser.START_TAG: 
                    if ("person".equals(parser.getName())) { 
                        person = new Person(); 
                        person.setId(Integer.parseInt(parser.getAttributeValue(0))); 
                    } 
                    if (("name").equals(parser.getName())) { 
                        person.setName(parser.nextText()); 
                    } 
                    if ("age".equals(parser.getName())) { 
                        person.setAge(Integer.parseInt(parser.nextText())); 
                    } 
                    break; 
                case XmlPullParser.END_TAG: 
                    if ("person".equals(parser.getName())) { 
                        persons.add(person); 
                        Log.i("person", person.toString()); 
                    } 
                    break; 
                } 
                event = parser.next(); 
            } 
        } 
        return persons; 
 
    } 

效果如下:

 

 作者:xiazdong

 

發佈留言