一、與服務器通信
類似於浏覽器與服務器通信,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打開)