Android数据转化为Xml形式给客户端及客户端使用xml数据

(1)创建实体类News

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

    public News(Integer id, String title, Integer timelength) {
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }
    //get、set方法
}

(2)面向接口编程所创建的接口可接口的实现类:

public interface VideoNewsService {
    /**
     * 获取最新的视频资讯
     * @return
     */
    public List<News> getLastNews();

}

接口的实现类,用于加入一些假数据

public class VideoNewsServiceBean implements VideoNewsService {

    public List<News> getLastNews(){
        List<News> newes = new ArrayList<News>();
        newes.add(new News(90, "喜羊羊与灰太狼全集", 78));
        newes.add(new News(10, "实拍舰载直升东海救援演习", 28));
        newes.add(new News(56, "喀麦隆VS荷兰", 70));
        return newes;
    }
}

(3)通过servlet返回数据大客户端

public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private VideoNewsService service = new VideoNewsServiceBean();

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

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        List<News> videos = service.getLastNews();
        request.setAttribute("videos", videos);
        //重定向一个jsp界面,当客户端请求的时候返回的是该jsp页面数据
        request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
    }
}

(4)生成xml文件的jsp页面(这里返回的为xml文件所以contentType=”text/xml”)

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

(5)在客户端中使用xml文件
同样的客户端同样需要一个News实体类,这里省略
创建一个service类用于解析xml和返回xml文件数据

public class VideoNewsService {
    /**
     * 获取最新的视频资讯
     */
    public static List<News> getLastNews() throws Exception{
        String path = "请求servlet的url";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream inStream = conn.getInputStream();
            return parseXML(inStream);
        }
        return null;
    }
    /**
     * 解析服务器返回的xml数据
<?xml version="1.0" encoding="UTF-8" ?> 
<videonews>
  <news id="35">
  <title>喜羊羊与灰太狼全集</title> 
  <timelength>90</timelength> 
  </news>
 <news id="12">
  <title>老张与灰太狼</title> 
  <timelength>20</timelength> 
  </news>
 <news id="56">
  <title>老方与LILI</title> 
  <timelength>30</timelength> 
  </news>
</videonews>
     */
    private static List<News> parseXML(InputStream inStream) throws Exception {
        List<News> newses = new ArrayList<News>();
        News news = null;
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(inStream, "UTF-8");
        int event = parser.getEventType();
        //对xml解析器的事件进行判断
        while( event != XmlPullParser.END_DOCUMENT){
            switch (event) {
            case XmlPullParser.START_TAG:
                if("news".equals(parser.getName())){
                    int id = new Integer(parser.getAttributeValue(0));
                    news = new News();
                    news.setId(id);
                }else if("title".equals(parser.getName())){
                    news.setTitle(parser.nextText());
                }else if("timelength".equals(parser.getName())){
                    news.setTimelength(new Integer(parser.nextText()));
                }
                break;

            case XmlPullParser.END_TAG:
                if("news".equals(parser.getName())){
                    newses.add(news);
                    news = null;
                }
                break;
            }
            event = parser.next();
        }
        return newses;
    }
}

(6)在Mainactivity.java文件中使用(这里是为一个listview设置值)

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView listView = (ListView) this.findViewById(R.id.listView);
        try {
            List<News> videos = VideoNewsService.getLastNews();//需修改成你本机的Http请求路径
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
            for(News news : videos){
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put("timelength", getResources().getString(R.string.timelength)
                        + news.getTimelength()+ getResources().getString(R.string.min));
                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 (Exception e) {
            e.printStackTrace();
        }
    }
}

到此完成操作

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。