android-servlet 返回xml

用户通过访问web资源的最新电影资讯,服务器端生成XML或JSON格式数据,返回Android客户端进行显示。

此案例开发需要两个方面 WEB开发和android开发.

一.web开发相对比较简单,只是模拟一下

相关代码如下:

1.实体Bean

package ygc.yxb.domain;

/**
 * 电影资讯实体Bean
 * @author YXB
 *
 */
public class News {
    private Integer id;              //id
    private String title;        //电影名称
    private Integer timelenght; //时长
    
    
    public News() {
        
    }
    
    
    public News(Integer id, String title, Integer timelenght) {
        this.id = id;
        this.title = title;
        this.timelenght = timelenght;
    }

    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 getTimelenght() {
        return timelenght;
    }
    public void setTimelenght(Integer timelenght) {
        this.timelenght = timelenght;
    }
    
    

}

2.业务逻辑

 

package ygc.yxb.service.impl;

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

import ygc.yxb.domain.News;
import ygc.yxb.service.VideoNewsService;

public class VideoNewsServiceImpl implements VideoNewsService {
    
    
    /**
     * 获取电影资讯的业务方法
     */
    public List<News> getLastNews(){
        
        
        List<News> newses = new ArrayList<News>();
        newses.add(new News(32, "大话西游", 90));
        newses.add(new News(12, "轩辕剑", 40));
        newses.add(new News(56, "爱情公寓", 30));
        return newses;
        
    }

}

 

3.Servlet

 

package ygc.yxb.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 ygc.yxb.domain.News;
import ygc.yxb.service.VideoNewsService;
import ygc.yxb.service.impl.VideoNewsServiceImpl;

/**
 * 用最原始的web开发servlet请求服务器,并返回客户端数据
 */
public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private VideoNewsService service = new VideoNewsServiceImpl();
   
    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();
        String format=request.getParameter("format");
        //如果用户请求的是这个路径,则返回JSON格式的数据.http://192.168.1.113:8080/videonews/ListServlet?format=json
        
        if("json".equals(format)){
            //[{id:56,title:"xxxx",timelength:90}]
            //组拼一个JSON格式的对象
            StringBuilder builder = new StringBuilder();
            builder.append('[');
                for (News news : videos) {
                    builder.append('{');
                        builder.append("id:").append(news.getId()).append(',');
                        builder.append("title:\"").append(news.getTitle()).append("\",");
                        builder.append("timelength:").append(news.getTimelenght());
                    builder.append("},");
                }
                builder.deleteCharAt(builder.length()-1);
            builder.append(']');
            
            request.setAttribute("json", builder.toString());
            request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response);
            
            
        //如果用户请求的是这个路径,则返回XML格式的数据.http://192.168.1.113:8080/videonews/ListServlet
        }else{
            request.setAttribute("videos", videos);
            request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
        }
    }

}

 

4.jsp页面

4.1.jsonvideonews.jsp

<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}

获取数据

 

package ygc.yxb.service;

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

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import ygc.yxb.domain.News;
import ygc.yxb.utils.StreamTool;

public class VideoNewsService {
    
    /**
     * 获取最新的视频资讯接受服务器端XML格式的数据
     * @return
     * @throws Exception
     */
    public static List<News> getLastNews() throws Exception{
        String path="http://192.168.1.113:8080/videonews/ListServlet";
        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;
    }
    
    /**
     * 获取最新的视频资讯 接受服务器端JSON格式的数据
     * @return
     * @throws Exception
     */
    public static List<News> getJSONLastNews() throws Exception{
        String path="http://192.168.1.113:8080/videonews/ListServlet?format=json";
        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 parseJSON(inStream);
        }
        return null;
    }

    /**
     * 解析JSON数据
     * @param inStream
     * @return
     */
    private static List<News> parseJSON(InputStream inStream) throws Exception {
        List<News> newses = new ArrayList<News>();
        byte[] data =StreamTool.read(inStream);
        //将字节数组转换成字符串
        String json= new String(data);
        //将json对象转换成json的数组对象
        JSONArray array = new JSONArray(json);
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject=array.getJSONObject(i);
            News news=new News(jsonObject.getInt("id"),jsonObject.getString("title"),jsonObject.getInt("timelength"));
            newses.add(news);
        }
        
        return newses;
    }

    /**
     * 解析服务器返回的XML数据
     * @param inStream
     * @return
     */
    private static List<News> parseXML(InputStream inStream) throws Exception{
        List<News> newses = new ArrayList<News>();
        News news = null;
        //用Pull解析器解析XML文件
        XmlPullParser parser= Xml.newPullParser();
        parser.setInput(inStream, "UTF-8");
        
        //得到开始文档XML事件
        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.setTimelenght(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;
    }
    

}

 

 

 

 

posted @ 2013-12-06 12:36  可惜不是你  阅读(448)  评论(0编辑  收藏  举报