您的位置:首页 > 理论基础 > 计算机网络

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

2012-06-01 09:58 761 查看
jsonXMLAndroid网络协议资讯

1.服务器端代码样例:

Java代码

public class VideoListAction extends Action

{

private VideoService service = new VideoServiceBean();

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception

{

//得到最新的视频资讯

List<Video> videos = service.getLastVideos();

VideoForm formbean = (VideoForm)form;

if("json".equals(formbean.getFormat()))

{

//构建json字符串

StringBuilder json = new StringBuilder();

json.append('[');

for(Video video : 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());

return mapping.findForward("jsonvideo");

}

else

{

request.setAttribute("videos", videos);

return mapping.findForward("video");

}

}

}

Java代码

public class VideoServiceBean implements VideoService

{

public List<Video> getLastVideos() throws Exception

{

//理论上应该查询数据库

List<Video> videos = new ArrayList<Video>();

videos.add(new Video(78, "喜羊羊与灰太狼全集", 90));

videos.add(new Video(78, "实拍舰载直升东海救援演习", 20));

videos.add(new Video(78, "喀麦隆VS荷兰", 30));

return videos;

}

}

Java代码

public class VideoListAction extends Action

{

private VideoService service = new VideoServiceBean();

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception

{

//得到最新的视频资讯

List<Video> videos = service.getLastVideos();

VideoForm formbean = (VideoForm)form;

if("json".equals(formbean.getFormat()))

{

//构建json字符串

StringBuilder json = new StringBuilder();

json.append('[');

for(Video video : 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());

return mapping.findForward("jsonvideo");

}

else

{

request.setAttribute("videos", videos);

return mapping.findForward("video");

}

}

}

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

Java代码

public class VideoService

{

/**

* 以XML方式返回获取最新的资讯

* @return

* @throws Exception

*/

public static List<Video> getLastVideos() throws Exception

{

//确定请求服务器的地址

//注意在Android模拟器中访问本机服务器时不可以使用localhost与127字段

//因为模拟器本身是使用localhost绑定

String path = "http://192.168.1.100:8080/videoweb/video/list.do";

//建立一个URL对象

URL url = new URL(path);

//得到打开的链接对象

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

//设置请求超时与请求方式

conn.setReadTimeout(5*1000);

conn.setRequestMethod("GET");

//从链接中获取一个输入流对象

InputStream inStream = conn.getInputStream();

//对输入流进行解析

return parseXML(inStream);

}

/**

* 解析服务器返回的协议,得到资讯

* @param inStream

* @return

* @throws Exception

*/

private static List<Video> parseXML(InputStream inStream) throws Exception

{

List<Video> videos = null;

Video video = null;

//使用XmlPullParser

XmlPullParser parser = Xml.newPullParser();

parser.setInput(inStream, "UTF-8");

int eventType = parser.getEventType();//产生第一个事件

//只要不是文档结束事件

while(eventType!=XmlPullParser.END_DOCUMENT)

{

switch (eventType)

{

case XmlPullParser.START_DOCUMENT:

videos = new ArrayList<Video>();

break;

case XmlPullParser.START_TAG:

//获取解析器当前指向的元素的名称

String name = parser.getName();

if("video".equals(name))

{

video = new Video();

//把id属性写入

video.setId(new Integer(parser.getAttributeValue(0)));

}

if(video!=null)

{

if("title".equals(name))

{

//获取解析器当前指向元素的下一个文本节点的值

video.setTitle(parser.nextText());

}

if("timelength".equals(name))

{

//获取解析器当前指向元素的下一个文本节点的值

video.setTime(new Integer(parser.nextText()));

}

}

break;

case XmlPullParser.END_TAG:

if("video".equals(parser.getName()))

{

videos.add(video);

video = null;

}

break;

}

eventType = parser.next();

}

return videos;

}

/**

* 以Json方式返回获取最新的资讯,不需要手动解析,JSON自己会进行解析

* @return

* @throws Exception

*/

public static List<Video> getJSONLastVideos() throws Exception

{

//

List<Video> videos = new ArrayList<Video>();

//

String path = "http://192.168.1.100:8080/videoweb/video/list.do?format=json";

//建立一个URL对象

URL url = new URL(path);

//得到打开的链接对象

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

//设置请求超时与请求方式

conn.setReadTimeout(5*1000);

conn.setRequestMethod("GET");

//从链接中获取一个输入流对象

InputStream inStream = conn.getInputStream();

//调用数据流处理方法

byte[] data = StreamTool.readInputStream(inStream);

String json = new String(data);

//构建JSON数组对象

JSONArray array = new JSONArray(json);

//从JSON数组对象读取数据

for(int i=0 ; i < array.length() ; i++)

{

//获取各个属性的值

JSONObject item = array.getJSONObject(i);

int id = item.getInt("id");

String title = item.getString("title");

int timelength = item.getInt("timelength");

//构造的对象加入集合当中

videos.add(new Video(id, title, timelength));

}

return videos;

}

}

Java代码

public class StreamTool

{

/**

* 从输入流中获取数据

* @param inStream 输入流

* @return

* @throws Exception

*/

public static byte[] readInputStream(InputStream inStream) throws Exception{

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while( (len=inStream.read(buffer)) != -1 ){

outStream.write(buffer, 0, len);

}

inStream.close();

return outStream.toByteArray();

}

}

Java代码

public class MainActivity extends Activity

{

private ListView listView;

@Override

public void onCreate(Bundle savedInstanceState)

{

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 = new ArrayList<HashMap<String,Object>>();

//迭代传入

for(Video video : videos)

{

//把video中的数据绑定到item中

HashMap<String, Object> item = new HashMap<String, Object>();

item.put("id", video.getId());

item.put("title", video.getTitle());

item.put("timelength", "时长:"+ video.getTime());

data.add(item);

}

//使用SimpleAdapter处理ListView显示数据

SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,

new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});

//

listView.setAdapter(adapter);

}

catch (Exception e)

{

Toast.makeText(MainActivity.this, "获取最新视频资讯失败", 1).show();

Log.e("MainActivity", e.toString());

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐