zoukankan      html  css  js  c++  java
  • Android 进行解析并显示服务端返回的数据

    例子说明:用户通过访问web资源的最新电影资讯,服务器端生成XML或JSON格式数据,返回Android客户端进行显示。 此案例开发需要两个方面 WEB开发和Android开发. 一.web开发相对比较简单,只是模拟一下 相关代码如下: 1.实体Bean

    1. package ygc.yxb.domain;[/font]
    2. /**
    3. * 电影资讯实体Bean
    4. * @author YXB
    5. *
    6. */
    7. public class News {
    8.     private Integer id;              //id
    9.     private String title;        //电影名称
    10.     private Integer timelenght; //时长
    11.     public News() {
    12.         
    13.     }
    14.     public News(Integer id, String title, Integer timelenght) {
    15.         this.id = id;
    16.         this.title = title;
    17.         this.timelenght = timelenght;
    18.     }
    19.   public Integer getId() {
    20.         return id;
    21.     }
    22.     public void setId(Integer id) {
    23.         this.id = id;
    24.     }
    25.     public String getTitle() {
    26.         return title;
    27.     }
    28.     public void setTitle(String title) {
    29.         this.title = title;
    30.     }
    31.     public Integer getTimelenght() {
    32.         return timelenght;
    33.     }
    34.     public void setTimelenght(Integer timelenght) {
    35.         this.timelenght = timelenght;
    36.     }

    2.业务逻辑

    1. package ygc.yxb.service.impl;[/font]
    2. import java.util.ArrayList;
    3. import java.util.List;[/font]
    4. import ygc.yxb.domain.News;
    5. import ygc.yxb.service.VideoNewsService;[/font]
    6. public class VideoNewsServiceImpl implements VideoNewsService {
    7.       
    8.     /**
    9.      * 获取电影资讯的业务方法
    10.      */
    11.     public List<News> getLastNews(){
    12.         
    13.         
    14.         List<News> newses = new ArrayList<News>();
    15.         newses.add(new News(32, "大话西游", 90));
    16.         newses.add(new News(12, "轩辕剑", 40));
    17.         newses.add(new News(56, "爱情公寓", 30));
    18.         return newses;
    19.         
    20.     }

    3.Servlet

    1. package ygc.yxb.servlet;[/font]
    2. import java.io.IOException;
    3. import java.util.List;[/font]
    4. import javax.servlet.ServletException;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;[/font]
    8. import ygc.yxb.domain.News;
    9. import ygc.yxb.service.VideoNewsService;
    10. import ygc.yxb.service.impl.VideoNewsServiceImpl;[/font]
    11. /**
    12. * 用最原始的web开发servlet请求服务器,并返回客户端数据
    13. */
    14. public class ListServlet extends HttpServlet {
    15.     private static final long serialVersionUID = 1L;
    16.     private VideoNewsService service = new VideoNewsServiceImpl();
    17.    
    18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19.         doPost(request, response);
    20.     }
    21.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    22.         
    23.         List<News> videos = service.getLastNews();
    24.         String format=request.getParameter("format");
    25.         //如果用户请求的是这个路径,则返回JSON格式的数据.http://192.168.1.113:8080/videonews/ListServlet?format=json
    26.         
    27.         if("json".equals(format)){
    28.             //[{id:56,title:"xxxx",timelength:90}]
    29.             //组拼一个JSON格式的对象
    30.             StringBuilder builder = new StringBuilder();
    31.             builder.append('[');
    32.                 for (News news : videos) {
    33.                     builder.append('{');
    34.                         builder.append("id:").append(news.getId()).append(',');
    35.                         builder.append("title:"").append(news.getTitle()).append("",");
    36.                         builder.append("timelength:").append(news.getTimelenght());
    37.                     builder.append("},");
    38.                 }
    39.                 builder.deleteCharAt(builder.length()-1);
    40.             builder.append(']');
    41.             
    42.             request.setAttribute("json", builder.toString());
    43.             request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response);
    44.             
    45.             
    46.         //如果用户请求的是这个路径,则返回XML格式的数据.http://192.168.1.113:8080/videonews/ListServlet
    47.         }else{
    48.             request.setAttribute("videos", videos);
    49.             request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
    50.         }
    51.     }

    4.jsp页面
    4.1.jsonvideonews.jsp

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

    4.2.videonews.jsp XML数据

    1. <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><[url=mailto:%@taglib]%@taglib[/url] uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><?xml version="1.0" encoding="UTF-8"?>
    2. <videonews>
    3.     <c:forEach items="${videos}" var="video">
    4.         <news id ="${video.id }">
    5.             <title>${video.title }</title>
    6.             <timelength>${video.timelenght}</timelength>
    7.         </news>
    8.     </c:forEach>
    9. </videonews>

    到此为止web开发完毕,现在Android开发相关代码 1.实体Bean

    1. package ygc.yxb.domain;
    2. public class News {
    3.     private Integer id;
    4.     private String title;
    5.     private Integer timelenght;
    6.     public News() {
    7.         
    8.     }
    9.     public News(Integer id, String title, Integer timelenght) {
    10.         this.id = id;
    11.         this.title = title;
    12.         this.timelenght = timelenght;
    13.     }
    14.     public Integer getId() {
    15.         return id;
    16.     }
    17.     public void setId(Integer id) {
    18.         this.id = id;
    19.     }
    20.     public String getTitle() {
    21.         return title;
    22.     }
    23.     public void setTitle(String title) {
    24.         this.title = title;
    25.     }
    26.     public Integer getTimelenght() {
    27.         return timelenght;
    28.     }
    29.     public void setTimelenght(Integer timelenght) {
    30.         this.timelenght = timelenght;
    31.     }
    32. }

    2.业务逻辑

    1. package ygc.yxb.service;
    2. import java.io.InputStream;
    3. import java.net.HttpURLConnection;
    4. import java.net.URL;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import org.json.JSONArray;
    8. import org.json.JSONObject;
    9. import org.xmlpull.v1.XmlPullParser;
    10. import android.util.Xml;
    11. import ygc.yxb.domain.News;
    12. import ygc.yxb.utils.StreamTool;
    13. public class VideoNewsService {
    14.    
    15.     /**
    16.      * 获取最新的视频资讯接受服务器端XML格式的数据
    17.      * @return
    18.      * @throws Exception
    19.      */
    20.     public static List<News> getLastNews() throws Exception{
    21.         String path="http://192.168.1.113:8080/videonews/ListServlet";
    22.         URL url = new URL(path);
    23.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    24.         conn.setConnectTimeout(5000);
    25.         conn.setRequestMethod("GET");
    26.         if(conn.getResponseCode()==200){
    27.             InputStream inStream=conn.getInputStream();
    28.             return parseXML(inStream);
    29.         }
    30.         return null;
    31.     }
    32.    
    33.     /**
    34.      * 获取最新的视频资讯 接受服务器端JSON格式的数据
    35.      * @return
    36.      * @throws Exception
    37.      */
    38.     public static List<News> getJSONLastNews() throws Exception{
    39.         String path="http://192.168.1.113:8080/videonews/ListServlet?format=json";
    40.         URL url = new URL(path);
    41.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    42.         conn.setConnectTimeout(5000);
    43.         conn.setRequestMethod("GET");
    44.         if(conn.getResponseCode()==200){
    45.             InputStream inStream=conn.getInputStream();
    46.             return parseJSON(inStream);
    47.         }
    48.         return null;
    49.     }
    50.     /**
    51.      * 解析JSON数据
    52.      * @param inStream
    53.      * @return
    54.      */
    55.     private static List<News> parseJSON(InputStream inStream) throws Exception {
    56.         List<News> newses = new ArrayList<News>();
    57.         byte[] data =StreamTool.read(inStream);
    58.         //将字节数组转换成字符串
    59.         String json= new String(data);
    60.         //将json对象转换成json的数组对象
    61.         JSONArray array = new JSONArray(json);
    62.         for (int i = 0; i < array.length(); i++) {
    63.             JSONObject jsonObject=array.getJSONObject(i);
    64.             News news=new News(jsonObject.getInt("id"),jsonObject.getString("title"),jsonObject.getInt("timelength"));
    65.             newses.add(news);
    66.         }
    67.         
    68.         return newses;
    69.     }
    70.     /**
    71.      * 解析服务器返回的XML数据
    72.      * @param inStream
    73.      * @return
    74.      */
    75.     private static List<News> parseXML(InputStream inStream) throws Exception{
    76.         List<News> newses = new ArrayList<News>();
    77.         News news = null;
    78.         //用Pull解析器解析XML文件
    79.         XmlPullParser parser= Xml.newPullParser();
    80.         parser.setInput(inStream, "UTF-8");
    81.         
    82.         //得到开始文档XML事件
    83.         int event = parser.getEventType();
    84.         
    85.         //不等于结束事件,循环读取XML文件并封装成对象
    86.         while(event !=XmlPullParser.END_DOCUMENT){
    87.             switch (event) {
    88.             case XmlPullParser.START_TAG:
    89.                 if("news".equals(parser.getName())){
    90.                     int id = new Integer(parser.getAttributeValue(0));
    91.                     news = new News();
    92.                     news.setId(id);
    93.                     
    94.                 }else if("title".equals(parser.getName())){
    95.                     
    96.                     news.setTitle(parser.nextText());
    97.                     
    98.                 }else if("timelength".equals(parser.getName())){
    99.                     
    100.                     news.setTimelenght(new Integer(parser.nextText()));
    101.                 }
    102.                
    103.                 break;
    104.             case XmlPullParser.END_TAG:
    105.                 if("news".equals(parser.getName())){
    106.                     
    107.                     newses.add(news);
    108.                     news = null;
    109.                 }
    110.                 break;
    111.             }
    112.             
    113.             event = parser.next();
    114.         }
    115.         
    116.         return newses;
    117.     }
    118.    
    119. }

    3.Activity

    1. package ygc.yxb.news;
    2. import java.util.ArrayList;
    3. import java.util.HashMap;
    4. import java.util.List;
    5. import ygc.yxb.domain.News;
    6. import ygc.yxb.service.VideoNewsService;
    7. import android.app.Activity;
    8. import android.os.Bundle;
    9. import android.widget.ListView;
    10. import android.widget.SimpleAdapter;
    11. public class MainActivity extends Activity {
    12.     /** Called when the activity is first created. */
    13.     @Override
    14.     public void onCreate(Bundle savedInstanceState) {
    15.         super.onCreate(savedInstanceState);
    16.         setContentView(R.layout.main);
    17.         
    18.         ListView listView=(ListView)this.findViewById(R.id.listView);
    19.         
    20.         try {
    21.             List<News> videos=VideoNewsService.getJSONLastNews();
    22.             List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>();
    23.             for (News news : videos) {
    24.                 HashMap<String, Object> item = new HashMap<String, Object>();
    25.                 item.put("id", news.getId());
    26.                 item.put("title", news.getTitle());
    27.                 item.put("timelength", getResources().getString(R.string.timelength)+
    28.                         news.getTimelenght()+getResources().getString(R.string.min));
    29.                 data.add(item);
    30.                
    31.             }
    32.             //用SimpleAdapter 绑定ListView控件
    33.             SimpleAdapter adapter = new SimpleAdapter(this,data,
    34.                     R.layout.item,new String[]{"title","timelength"},
    35.                     new int[]{R.id.title,R.id.timelength});
    36.             listView.setAdapter(adapter);
    37.         } catch (Exception e) {
    38.             e.printStackTrace();
    39.         }
    40.     }
    41. }

    4读取数据流工具类:

    1. package ygc.yxb.utils;
    2. import java.io.ByteArrayOutputStream;
    3. import java.io.InputStream;
    4. public class StreamTool {
    5.     /**
    6.      * 读取流中的数据
    7.      * @param inStream
    8.      * @return
    9.      * @throws Exception
    10.      */
    11.     public static byte[] read(InputStream inStream) throws Exception {
    12.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    13.         byte[] buffer = new byte[1024];
    14.         int len = 0;
    15.         //如果字节流中的数据不等于-1,就说明一直有,然后循环读出
    16.         while( (len=inStream.read(buffer)) !=-1){
    17.             //将读出的数据放入内存中
    18.             outputStream.write(buffer);
    19.             
    20.         }
    21.         inStream.close();
    22.         return outputStream.toByteArray();
    23.     }
    24. }

    这里Android 开发完毕,而显示的控件是ListView 最后在清单文件中,配置访问网络的权限即可。 

  • 相关阅读:
    利用string 字符串拷贝
    新手学vim配置
    进程描述符task_struct
    并查集
    堆Heap
    Bitset位图
    排序
    sql时间查询
    javascript 中的 call
    css 笔记——设置禁用中文输入法
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/3468491.html
Copyright © 2011-2022 走看看