Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回

1.服务器端代码样例:

Java代码 复制代码
  1. public class VideoListAction extends Action  
  2.     private VideoService service = new VideoServiceBean(); 
  3.     public ActionForward execute(ActionMapping mapping, ActionForm form, 
  4.             HttpServletRequest request, HttpServletResponse response) 
  5.             throws Exception  
  6.     { 
  7.         //得到最新的视频资讯 
  8.         List<Video> videos = service.getLastVideos(); 
  9.         VideoForm formbean = (VideoForm)form; 
  10.         if("json".equals(formbean.getFormat())) 
  11.         { 
  12.             //构建json字符串 
  13.             StringBuilder json = new StringBuilder(); 
  14.             json.append('['); 
  15.             for(Video video : videos) 
  16.             { // 需要构造的形式是{id:76,title:"xxxx",timelength:80} 
  17.                 json.append('{'); 
  18.                 json.append("id:").append(video.getId()).append(','); 
  19.                 json.append("title:\"").append(video.getTitle()).append("\","); 
  20.                 json.append("timelength:").append(video.getTime()); 
  21.                 json.append('}').append(','); 
  22.             } 
  23.             json.deleteCharAt(json.length()-1); 
  24.             json.append(']'); 
  25.             //把json字符串放置于request 
  26.             request.setAttribute("json", json.toString()); 
  27.             return mapping.findForward("jsonvideo"); 
  28.         } 
  29.         else 
  30.         {            
  31.             request.setAttribute("videos", videos); 
  32.             return mapping.findForward("video"); 
  33.         } 
  34.     } 

Java代码 复制代码
  1. public class VideoServiceBean implements VideoService  
  2.     public List<Video> getLastVideos() throws Exception 
  3.     { 
  4.         //理论上应该查询数据库 
  5.         List<Video> videos = new ArrayList<Video>(); 
  6.         videos.add(new Video(78, "喜羊羊与灰太狼全集", 90)); 
  7.         videos.add(new Video(78, "实拍舰载直升东海救援演习", 20)); 
  8.         videos.add(new Video(78, "喀麦隆VS荷兰", 30)); 
  9.         return videos; 
  10.     } 

Java代码 复制代码
  1. public class VideoListAction extends Action  
  2.     private VideoService service = new VideoServiceBean(); 
  3.     public ActionForward execute(ActionMapping mapping, ActionForm form, 
  4.             HttpServletRequest request, HttpServletResponse response) 
  5.             throws Exception  
  6.     { 
  7.         //得到最新的视频资讯 
  8.         List<Video> videos = service.getLastVideos(); 
  9.         VideoForm formbean = (VideoForm)form; 
  10.         if("json".equals(formbean.getFormat())) 
  11.         { 
  12.             //构建json字符串 
  13.             StringBuilder json = new StringBuilder(); 
  14.             json.append('['); 
  15.             for(Video video : videos) 
  16.             { // 需要构造的形式是{id:76,title:"xxxx",timelength:80} 
  17.                 json.append('{'); 
  18.                 json.append("id:").append(video.getId()).append(','); 
  19.                 json.append("title:\"").append(video.getTitle()).append("\","); 
  20.                 json.append("timelength:").append(video.getTime()); 
  21.                 json.append('}').append(','); 
  22.             } 
  23.             json.deleteCharAt(json.length()-1); 
  24.             json.append(']'); 
  25.             //把json字符串放置于request 
  26.             request.setAttribute("json", json.toString()); 
  27.             return mapping.findForward("jsonvideo"); 
  28.         } 
  29.         else 
  30.         {            
  31.             request.setAttribute("videos", videos); 
  32.             return mapping.findForward("video"); 
  33.         } 
  34.     } 

2.客户端:使用XML方式与JSON方式返回数据

Java代码 复制代码
  1. public class VideoService  
  2.     /**
  3.      * 以XML方式返回获取最新的资讯
  4.      * @return
  5.      * @throws Exception
  6.      */ 
  7.     public static List<Video> getLastVideos() throws Exception 
  8.     { 
  9.         //确定请求服务器的地址 
  10.         //注意在Android模拟器中访问本机服务器时不可以使用localhost与127字段 
  11.         //因为模拟器本身是使用localhost绑定 
  12.         String path = "http://192.168.1.100:8080/videoweb/video/list.do"
  13.         //建立一个URL对象 
  14.         URL url = new URL(path); 
  15.         //得到打开的链接对象 
  16.         HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
  17.         //设置请求超时与请求方式 
  18.         conn.setReadTimeout(5*1000); 
  19.         conn.setRequestMethod("GET"); 
  20.         //从链接中获取一个输入流对象 
  21.         InputStream inStream = conn.getInputStream(); 
  22.         //对输入流进行解析 
  23.         return parseXML(inStream); 
  24.     } 
  25.      
  26.     /**
  27.      * 解析服务器返回的协议,得到资讯
  28.      * @param inStream
  29.      * @return
  30.      * @throws Exception
  31.      */ 
  32.     private static List<Video> parseXML(InputStream inStream) throws Exception 
  33.     { 
  34.         List<Video> videos = null
  35.         Video video = null
  36.         //使用XmlPullParser 
  37.         XmlPullParser parser = Xml.newPullParser(); 
  38.         parser.setInput(inStream, "UTF-8"); 
  39.         int eventType = parser.getEventType();//产生第一个事件 
  40.         //只要不是文档结束事件 
  41.         while(eventType!=XmlPullParser.END_DOCUMENT) 
  42.         { 
  43.             switch (eventType)  
  44.             { 
  45.                 case XmlPullParser.START_DOCUMENT: 
  46.                     videos = new ArrayList<Video>(); 
  47.                     break;       
  48.                      
  49.                 case XmlPullParser.START_TAG: 
  50.                     //获取解析器当前指向的元素的名称 
  51.                     String name = parser.getName(); 
  52.                     if("video".equals(name)) 
  53.                     { 
  54.                         video = new Video(); 
  55.                         //把id属性写入 
  56.                         video.setId(new Integer(parser.getAttributeValue(0))); 
  57.                     } 
  58.                     if(video!=null
  59.                     { 
  60.                         if("title".equals(name)) 
  61.                         { 
  62.                             //获取解析器当前指向元素的下一个文本节点的值 
  63.                             video.setTitle(parser.nextText()); 
  64.                         } 
  65.                         if("timelength".equals(name)) 
  66.                         { 
  67.                             //获取解析器当前指向元素的下一个文本节点的值 
  68.                             video.setTime(new Integer(parser.nextText())); 
  69.                         } 
  70.                     } 
  71.                     break
  72.                      
  73.                 case XmlPullParser.END_TAG: 
  74.                     if("video".equals(parser.getName())) 
  75.                     { 
  76.                         videos.add(video); 
  77.                         video = null
  78.                     } 
  79.                     break
  80.             } 
  81.             eventType = parser.next(); 
  82.         } 
  83.         return videos; 
  84.     } 
  85.      
  86.     /**
  87.      * 以Json方式返回获取最新的资讯,不需要手动解析,JSON自己会进行解析
  88.      * @return
  89.      * @throws Exception
  90.      */ 
  91.     public static List<Video> getJSONLastVideos() throws Exception 
  92.     { 
  93.         // 
  94.         List<Video> videos = new ArrayList<Video>(); 
  95.         // 
  96.         String path = "http://192.168.1.100:8080/videoweb/video/list.do?format=json"
  97.         //建立一个URL对象 
  98.         URL url = new URL(path); 
  99.         //得到打开的链接对象 
  100.         HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
  101.         //设置请求超时与请求方式 
  102.         conn.setReadTimeout(5*1000); 
  103.         conn.setRequestMethod("GET"); 
  104.         //从链接中获取一个输入流对象 
  105.         InputStream inStream = conn.getInputStream(); 
  106.         //调用数据流处理方法 
  107.         byte[] data = StreamTool.readInputStream(inStream); 
  108.         String json = new String(data); 
  109.         //构建JSON数组对象 
  110.         JSONArray array = new JSONArray(json); 
  111.         //从JSON数组对象读取数据 
  112.         for(int i=0 ; i < array.length() ; i++) 
  113.         { 
  114.             //获取各个属性的值 
  115.             JSONObject item = array.getJSONObject(i); 
  116.             int id = item.getInt("id"); 
  117.             String title = item.getString("title"); 
  118.             int timelength = item.getInt("timelength"); 
  119.             //构造的对象加入集合当中 
  120.             videos.add(new Video(id, title, timelength)); 
  121.         } 
  122.         return videos; 
  123.     } 

Java代码 复制代码
  1. public class StreamTool  
  2.     /**
  3.      * 从输入流中获取数据
  4.      * @param inStream 输入流
  5.      * @return
  6.      * @throws Exception
  7.      */ 
  8.     public static byte[] readInputStream(InputStream inStream) throws Exception{ 
  9.         ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
  10.         byte[] buffer = new byte[1024]; 
  11.         int len = 0
  12.         while( (len=inStream.read(buffer)) != -1 ){ 
  13.             outStream.write(buffer, 0, len); 
  14.         } 
  15.         inStream.close(); 
  16.         return outStream.toByteArray(); 
  17.     } 

Java代码 复制代码
  1. public class MainActivity extends Activity  
  2.     private ListView listView; 
  3.     @Override 
  4.     public void onCreate(Bundle savedInstanceState)  
  5.     { 
  6.         super.onCreate(savedInstanceState); 
  7.         setContentView(R.layout.main); 
  8.         //获取到ListView对象 
  9.         listView = (ListView)this.findViewById(R.id.listView); 
  10.         try  
  11.         { 
  12.             //通过 
  13.             List<Video> videos = VideoService.getLastVideos(); 
  14.             //通过Json方式获取视频内容 
  15.             //List<Video> videos2 = VideoService.getJSONLastVideos(); 
  16.             // 
  17.             List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>(); 
  18.             //迭代传入 
  19.             for(Video video : videos) 
  20.             { 
  21.                 //把video中的数据绑定到item中 
  22.                 HashMap<String, Object> item = new HashMap<String, Object>(); 
  23.                 item.put("id", video.getId()); 
  24.                 item.put("title", video.getTitle()); 
  25.                 item.put("timelength", "时长:"+ video.getTime()); 
  26.                 data.add(item); 
  27.             } 
  28.             //使用SimpleAdapter处理ListView显示数据 
  29.             SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,  
  30.                     new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength}); 
  31.             // 
  32.             listView.setAdapter(adapter); 
  33.         }  
  34.         catch (Exception e)  
  35.         { 
  36.             Toast.makeText(MainActivity.this, "获取最新视频资讯失败", 1).show(); 
  37.             Log.e("MainActivity", e.toString()); 
  38.         }  
  39.     } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值