从网络获取xml格式的视频资讯

C.案例,酷6网的视频客户端有一个功能:"在手机上显示最新的视频资讯",
视频资讯是从服务器获取的,数据以xml格式返回给android客户端,然后列表
显示在手机上;

http://192.168.1.100:8080/videowebxml/video/list.do

<?xml version="1.0" encoding="UTF-8"?>
<videos>
 <video id="78">
  <title>喜羊羊与灰太狼全集</title>
  <timelength>90</timelength>
 </video>
 <video id="78">
  <title>实拍舰载直升东海救援演习</title>
  <timelength>20</timelength>
 </video>
 <video id="78">
  <title>喀麦隆VS荷兰</title>
  <timelength>30</timelength>
 </video>
</videos>

下面的代码是搭建web服务器:

 

web.xml-----------使用struts1

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	
  	<servlet>
		<servlet-name>struts</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>struts</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>	
			
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>

	<action-mappings>
		<action path="/video/list" scope="request" type="cn.itcast.action.VideoListAction">
			<forward name="video" path="/WEB-INF/page/videos.jsp"/>
		</action>

	</action-mappings>
</struts-config>


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>


Video.java

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;
	}
	
}

VideoService.java

package cn.itcast.service;

import java.util.List;

import cn.itcast.domain.Video;

public interface VideoService {

	/**
	 * 返回最新的视频资讯
	 * @return
	 * @throws Exception
	 */
	public List<Video> getLastVideos() throws Exception;

}

VideoServiceBean.java

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;
	}
}

VideoListAction.java

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.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<Video> videos = service.getLastVideos();
		//返回给客户端xml格式的数据;
				
		request.setAttribute("videos", videos);
		return mapping.findForward("video");
		
	}

}

 

下面是Android方面的代码:

 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView" />

</LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <TextView
   android:layout_width="250dip"
   android:layout_height="wrap_content"
   android:id="@+id/title"
  />
  
  <TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/timelength"
  />

</LinearLayout>

在AndroidManifest.xml中添加访问网络的权限
    <!-- 访问网络的权限 -->
	<uses-permission android:name="android.permission.INTERNET"/>


 

Video.java

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;
	}
	
}


StreamTool.java

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);//将buffer的数据写到内存中;
		}
		
		inStream.close();
		return outStream.toByteArray();
	}
}


VideoService.java

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.xmlpull.v1.XmlPullParser;
import cn.itcast.domain.Video;

import android.util.Xml;

public class VideoService {
	
	/**
	 * 获取最新的视频资讯
	 * @return
	 * @throws Exception
	 */
	public static List<Video> getLastVideos() throws Exception{
		String path = "http://192.168.1.100:8080/videowebxml/video/list.do";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5*1000);
		InputStream inStream = conn.getInputStream();
		return parseXML(inStream);
	}
	
	/**
	 * 解析服务器返回的协议,得到视频资讯
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public 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)));//获取video的属性id
				}
				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;
	}
}


 

MainActivity.java

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 cn.itcast.video.client.R;
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.getLastVideos();
		
		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());
	}
        
    }
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值