zoukankan      html  css  js  c++  java
  • Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回

    http://daimajishu.iteye.com/blog/1088626

    1.服务器端代码样例:

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

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

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

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

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

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

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

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    微信小程序TodoList
    C语言88案例-找出数列中的最大值和最小值
    C语言88案例-使用指针的指针输出字符串
  • 原文地址:https://www.cnblogs.com/meieiem/p/2186204.html
Copyright © 2011-2022 走看看