Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
16lz
2021-01-23
http://daimajishu.iteye.com/blog/1088626
转自:
Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
json XML Android 网络协议 资讯1.服务器端代码样例:
Java代码- publicclassVideoListActionextendsAction
- {
- privateVideoServiceservice=newVideoServiceBean();
- publicActionForwardexecute(ActionMappingmapping,ActionFormform,
- HttpServletRequestrequest,HttpServletResponseresponse)
- throwsException
- {
- //得到最新的视频资讯
- List<Video>videos=service.getLastVideos();
- VideoFormformbean=(VideoForm)form;
- if("json".equals(formbean.getFormat()))
- {
- //构建json字符串
- StringBuilderjson=newStringBuilder();
- json.append('[');
- for(Videovideo:videos)
- {//需要构造的形式是{id:76,title:"xxxx",timelength:80}
- json.append('{');
- json.append("id:").append(video.getId()).append(',');
- json.append("title:\"").append(video.getTitle()).append("\",");
- json.append("timelength:").append(video.getTime());
- json.append('}').append(',');
- }
- json.deleteCharAt(json.length()-1);
- json.append(']');
- //把json字符串放置于request
- request.setAttribute("json",json.toString());
- returnmapping.findForward("jsonvideo");
- }
- else
- {
- request.setAttribute("videos",videos);
- returnmapping.findForward("video");
- }
- }
- }
- publicclassVideoServiceBeanimplementsVideoService
- {
- publicList<Video>getLastVideos()throwsException
- {
- //理论上应该查询数据库
- List<Video>videos=newArrayList<Video>();
- videos.add(newVideo(78,"喜羊羊与灰太狼全集",90));
- videos.add(newVideo(78,"实拍舰载直升东海救援演习",20));
- videos.add(newVideo(78,"喀麦隆VS荷兰",30));
- returnvideos;
- }
- }
- publicclassVideoListActionextendsAction
- {
- privateVideoServiceservice=newVideoServiceBean();
- publicActionForwardexecute(ActionMappingmapping,ActionFormform,
- HttpServletRequestrequest,HttpServletResponseresponse)
- throwsException
- {
- //得到最新的视频资讯
- List<Video>videos=service.getLastVideos();
- VideoFormformbean=(VideoForm)form;
- if("json".equals(formbean.getFormat()))
- {
- //构建json字符串
- StringBuilderjson=newStringBuilder();
- json.append('[');
- for(Videovideo:videos)
- {//需要构造的形式是{id:76,title:"xxxx",timelength:80}
- json.append('{');
- json.append("id:").append(video.getId()).append(',');
- json.append("title:\"").append(video.getTitle()).append("\",");
- json.append("timelength:").append(video.getTime());
- json.append('}').append(',');
- }
- json.deleteCharAt(json.length()-1);
- json.append(']');
- //把json字符串放置于request
- request.setAttribute("json",json.toString());
- returnmapping.findForward("jsonvideo");
- }
- else
- {
- request.setAttribute("videos",videos);
- returnmapping.findForward("video");
- }
- }
- }
2.客户端:使用XML方式与JSON方式返回数据
Java代码- publicclassVideoService
- {
- /**
- *以XML方式返回获取最新的资讯
- *@return
- *@throwsException
- */
- publicstaticList<Video>getLastVideos()throwsException
- {
- //确定请求服务器的地址
- //注意在Android模拟器中访问本机服务器时不可以使用localhost与127字段
- //因为模拟器本身是使用localhost绑定
- Stringpath="http://192.168.1.100:8080/videoweb/video/list.do";
- //建立一个URL对象
- URLurl=newURL(path);
- //得到打开的链接对象
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- //设置请求超时与请求方式
- conn.setReadTimeout(5*1000);
- conn.setRequestMethod("GET");
- //从链接中获取一个输入流对象
- InputStreaminStream=conn.getInputStream();
- //对输入流进行解析
- returnparseXML(inStream);
- }
- /**
- *解析服务器返回的协议,得到资讯
- *@paraminStream
- *@return
- *@throwsException
- */
- privatestaticList<Video>parseXML(InputStreaminStream)throwsException
- {
- List<Video>videos=null;
- Videovideo=null;
- //使用XmlPullParser
- XmlPullParserparser=Xml.newPullParser();
- parser.setInput(inStream,"UTF-8");
- inteventType=parser.getEventType();//产生第一个事件
- //只要不是文档结束事件
- while(eventType!=XmlPullParser.END_DOCUMENT)
- {
- switch(eventType)
- {
- caseXmlPullParser.START_DOCUMENT:
- videos=newArrayList<Video>();
- break;
- caseXmlPullParser.START_TAG:
- //获取解析器当前指向的元素的名称
- Stringname=parser.getName();
- if("video".equals(name))
- {
- video=newVideo();
- //把id属性写入
- video.setId(newInteger(parser.getAttributeValue(0)));
- }
- if(video!=null)
- {
- if("title".equals(name))
- {
- //获取解析器当前指向元素的下一个文本节点的值
- video.setTitle(parser.nextText());
- }
- if("timelength".equals(name))
- {
- //获取解析器当前指向元素的下一个文本节点的值
- video.setTime(newInteger(parser.nextText()));
- }
- }
- break;
- caseXmlPullParser.END_TAG:
- if("video".equals(parser.getName()))
- {
- videos.add(video);
- video=null;
- }
- break;
- }
- eventType=parser.next();
- }
- returnvideos;
- }
- /**
- *以Json方式返回获取最新的资讯,不需要手动解析,JSON自己会进行解析
- *@return
- *@throwsException
- */
- publicstaticList<Video>getJSONLastVideos()throwsException
- {
- //
- List<Video>videos=newArrayList<Video>();
- //
- Stringpath="http://192.168.1.100:8080/videoweb/video/list.do?format=json";
- //建立一个URL对象
- URLurl=newURL(path);
- //得到打开的链接对象
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- //设置请求超时与请求方式
- conn.setReadTimeout(5*1000);
- conn.setRequestMethod("GET");
- //从链接中获取一个输入流对象
- InputStreaminStream=conn.getInputStream();
- //调用数据流处理方法
- byte[]data=StreamTool.readInputStream(inStream);
- Stringjson=newString(data);
- //构建JSON数组对象
- JSONArrayarray=newJSONArray(json);
- //从JSON数组对象读取数据
- for(inti=0;i<array.length();i++)
- {
- //获取各个属性的值
- JSONObjectitem=array.getJSONObject(i);
- intid=item.getInt("id");
- Stringtitle=item.getString("title");
- inttimelength=item.getInt("timelength");
- //构造的对象加入集合当中
- videos.add(newVideo(id,title,timelength));
- }
- returnvideos;
- }
- }
- publicclassStreamTool
- {
- /**
- *从输入流中获取数据
- *@paraminStream输入流
- *@return
- *@throwsException
- */
- publicstaticbyte[]readInputStream(InputStreaminStream)throwsException{
- ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
- byte[]buffer=newbyte[1024];
- intlen=0;
- while((len=inStream.read(buffer))!=-1){
- outStream.write(buffer,0,len);
- }
- inStream.close();
- returnoutStream.toByteArray();
- }
- }
- publicclassMainActivityextendsActivity
- {
- privateListViewlistView;
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //获取到ListView对象
- listView=(ListView)this.findViewById(R.id.listView);
- try
- {
- //通过
- List<Video>videos=VideoService.getLastVideos();
- //通过Json方式获取视频内容
- //List<Video>videos2=VideoService.getJSONLastVideos();
- //
- List<HashMap<String,Object>>data=newArrayList<HashMap<String,Object>>();
- //迭代传入
- for(Videovideo:videos)
- {
- //把video中的数据绑定到item中
- HashMap<String,Object>item=newHashMap<String,Object>();
- item.put("id",video.getId());
- item.put("title",video.getTitle());
- item.put("timelength","时长:"+video.getTime());
- data.add(item);
- }
- //使用SimpleAdapter处理ListView显示数据
- SimpleAdapteradapter=newSimpleAdapter(this,data,R.layout.item,
- newString[]{"title","timelength"},newint[]{R.id.title,R.id.timelength});
- //
- listView.setAdapter(adapter);
- }
- catch(Exceptione)
- {
- Toast.makeText(MainActivity.this,"获取最新视频资讯失败",1).show();
- Log.e("MainActivity",e.toString());
- }
- }
- }