zoukankan      html  css  js  c++  java
  • Android入门:通过XML数据与服务器进行通信


    一、与服务器通信


    类似于浏览器与服务器通信,Android应用也可以与Web服务器通信,比如Android应用可以访问Servlet、JSP、图片等等;

    Web服务器通过指定Content-Type可以指定返回的数据的类型,比如text/html表示网页,text/xml表示XML数据,image/jpeg为图片;


    二、通过XML让客户端和服务器交流数据





    比如Android客户端打开相亲网,则返回的是多个人的序列,包含人的姓名、年龄等信息,而怎么组织这些数据返回给客户端呢?用XML很方便;



    三、代码实现


    服务器使用了dom4j组织XML数据,并返回给客户端;

    代码结构如下:





    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中加入:

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

    每个item的布局如下:

    <?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

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

    效果如下:











  • 相关阅读:
    Mac下Android studio搭建Android开发环境【新手】
    2016年美国数学建模比赛(MCM/ICM) E题环境科学 Are we heading towards a thirsty planet? 人工精准翻译。
    一张图让你快速学会UML(聚合、组合、依赖、继承、接口、类)
    《黑客与画家》——读书笔记
    YC(Y Combinator)斯坦福大学《如何创业》课程要点记录(粗糙)
    《你的灯亮着吗?发现问题的真正所在》——读书笔记
    sublime使用
    spring AOP面向切面编程
    LinkedHashMap源码浅析jdk1.7
    增强型for循环与集合
  • 原文地址:https://www.cnblogs.com/xiazdong/p/3058328.html
Copyright © 2011-2022 走看看