首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android取得视频数据

2012-06-28 
Android获得视频数据一:服务器端代码1:Video package cn.itcast.domainpublic class Video {private Inte

Android获得视频数据

一:服务器端代码

1:Video

package cn.itcast.domain;public class Video {private Integer id;private String title;private Integer time;public Video(){}public Video(Integer id, String title, Integer time) {this.id = id;this.title = title;this.time = time;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getTime() {return time;}public void setTime(Integer time) {this.time = time;}}

?

2:VideoServiceBean

package cn.itcast.service.impl;import java.util.ArrayList;import java.util.List;import cn.itcast.domain.Video;import cn.itcast.service.VideoService;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;}}

?3:VideoListAction

package cn.itcast.action;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import cn.itcast.domain.Video;import cn.itcast.formbean.VideoForm;import cn.itcast.service.VideoService;import cn.itcast.service.impl.VideoServiceBean;public class VideoListAction extends Action {private VideoService service = new VideoServiceBean();public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {//list.do?format=jsonList<Video> videos = service.getLastVideos();VideoForm formbean = (VideoForm)form;if("json".equals(formbean.getFormat())){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(']');request.setAttribute("json", json.toString());return mapping.findForward("jsonvideo");}else{request.setAttribute("videos", videos);return mapping.findForward("video");}}}

5:struts-config.xml

  <?xml version="1.0" encoding="UTF-8" ?>   <!DOCTYPE struts-config (View Source for full doctype...)> - <struts-config>- <form-beans>  <form-bean name="videoForm" type="cn.itcast.formbean.VideoForm" />   </form-beans>- <action-mappings>- <action path="/video/list" name="videoForm" scope="request" type="cn.itcast.action.VideoListAction">  <forward name="video" path="/WEB-INF/page/videos.jsp" />   <forward name="jsonvideo" path="/WEB-INF/page/jsonvideos.jsp" />   </action>- <action path="/video/manage" name="videoForm" scope="request" type="cn.itcast.action.VideoManageAction" parameter="method">  <forward name="result" path="/WEB-INF/page/result.jsp" />   </action>  </action-mappings>  </struts-config>

?6:videos.jsp

<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><?xml version="1.0" encoding="UTF-8"?><videos><c:forEach items="${videos}" var="video"><video id="${video.id}"><title>${video.title}</title><timelength>${video.time}</timelength></video></c:forEach></videos>

7:jsonvideos.jsp

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

?

?二:客户端

1:Video

package cn.itcast.domain;public class Video {private Integer id;private String title;private Integer time;public Video(){}public Video(Integer id, String title, Integer time) {this.id = id;this.title = title;this.time = time;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getTime() {return time;}public void setTime(Integer time) {this.time = time;}}

??2:

package cn.itcast.utils;import java.io.ByteArrayOutputStream;import java.io.InputStream;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();}}

?

3:VideoService

package cn.itcast.service;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import org.json.JSONObject;import org.xmlpull.v1.XmlPullParser;import android.util.Xml;import cn.itcast.domain.Video;import cn.itcast.utils.StreamTool;public class VideoService {/** * 获取最新的视频资讯 * @return * @throws Exception */public static List<Video> getLastVideos() throws Exception{String path = "http://192.168.1.100:8080/videoweb/video/list.do";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setReadTimeout(5*1000);conn.setRequestMethod("GET");InputStream inStream = conn.getInputStream();return parseXML(inStream);}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 = 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);JSONArray array = new JSONArray(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;}/** * 解析服务器返回的协议,得到视频资讯 * @param inStream * @return * @throws Exception */private static List<Video> parseXML(InputStream inStream) throws Exception{List<Video> videos = null;Video video = null;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();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;}}

?

4:

package cn.itcast.videoclient;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import cn.itcast.domain.Video;import cn.itcast.service.VideoService;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity {    private ListView listView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                listView = (ListView)this.findViewById(R.id.listView);        try {List<Video> videos = VideoService.getJSONLastVideos();List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();for(Video video : videos){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 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());}     }}

?

热点排行