从服务器获取最新的视频资讯
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 Throwable
*/
publicstatic List<Video> getLastJSONVideos() throws Throwable{
ArrayList<Video>videos = new ArrayList<Video>();
Stringpath = "http://192.168.1.10:8080/videoweb/video/list.do?format=json";
URLurl = new URL(path);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
解析:每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字。
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
InputStreaminStream = conn.getInputStream();
byte[]data = StreamTool.readInputStream(inStream);
Stringjson = new String(data);
JSONArrayarray = new JSONArray(json);
for(inti = 0 ; i < array.length() ; i++){
JSONObjectitem = array.getJSONObject(i);
Videovideo = new Video(item.getInt("id"),item.getString("title"), item.getInt("timelength"));
videos.add(video);
}
returnvideos;
}
/**
* 从服务器获取最新的视频资讯
* @return
* @throws Throwable
*/
publicstatic List<Video> getLastVideos() throws Throwable{
Stringpath = "http://192.168.1.10:8080/videoweb/video/list.do";
URLurl = new URL(path);
HttpURLConnectionconn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
InputStreaminStream = conn.getInputStream();
returnparseXML(inStream);
}
privatestatic List<Video> parseXML(InputStream inStream) throws Exception{
Videovideo = null;
List<Video>videos = null;
XmlPullParserpullParser = Xml.newPullParser();
pullParser.setInput(inStream,"UTF-8");
intevent = pullParser.getEventType();//触发第一个事件
while(event!=XmlPullParser.END_DOCUMENT){
switch(event) {
caseXmlPullParser.START_DOCUMENT:
videos= new ArrayList<Video>();初始化对象
break;
caseXmlPullParser.START_TAG:
if("video".equals(pullParser.getName())){
intid = new Integer(pullParser.getAttributeValue(0));
video= new Video();
video.setId(id);
}
if(video!=null){
if("title".equals(pullParser.getName())){
video.setTitle(pullParser.nextText());
}
if("timelength".equals(pullParser.getName())){
video.setTimelength(newInteger(pullParser.nextText()));
}
}
break;
caseXmlPullParser.END_TAG:
if("video".equals(pullParser.getName())){
videos.add(video);
video= null;
}
break;
}
event= pullParser.next();
}
returnvideos;
}
}
测试方法
package cn.itcast.videonews;
import java.util.List;
import cn.itcast.domain.Video;
import cn.itcast.service.VideoService;
import android.test.AndroidTestCase;
import android.util.Log;
public class VideoServiceTest extendsAndroidTestCase {
privatestatic final String TAG = "VideoServiceTest";
publicvoid testGetLastVideos() throws Throwable{
List<Video>videos = VideoService.getLastVideos();
for(Videovideo : videos){
Log.i(TAG,video.toString());把信息打印到控制台
}
}
}
从输入流中读取数据
package cn.itcast.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 从输入流中读取数据
* @param inStream
* @return
* @throws Exception
*/
publicstatic byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();
解析:此类实现了一个输出流,其中的数据被写入一个byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用toByteArray()
和 toString()
获取数据。
关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException。
byte[]buffer = new byte[1024];
intlen = 0;
while((len = inStream.read(buffer)) !=-1 ){
outStream.write(buffer,0, len);
}
byte[]data = outStream.toByteArray();//获取网页的二进制数据
outStream.close();
inStream.close();
returndata;
}
}
package cn.itcast.videonews;
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 extendsActivity {
private static final String TAG = "MainActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
List<Video>videos = VideoService.getLastJSONVideos();//获取最新视频资讯
ListViewlistView = (ListView)this.findViewById(R.id.listView);
List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>();
for(Videovideo : videos){
HashMap<String,Object> item = new HashMap<String, Object>();
item.put("title",video.getTitle());
item.put("timelength","时长:"+video.getTimelength());
item.put("id",video.getId());
data.add(item);
}
SimpleAdapteradapter = new SimpleAdapter(this, data, R.layout.item,
newString[]{"title","timelength"}, new int[]{R.id.title,R.id.timelength});
listView.setAdapter(adapter);
}catch (Throwable e) {
Log.e(TAG,e.toString());
Toast.makeText(this,R.string.error, 1).show();
}
}
}
package cn.itcast.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 从输入流中读取数据
* @param inStream
* @return
* @throws Exception
*/
publicstatic byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();
byte[]buffer = new byte[1024];
intlen = 0;
while((len = inStream.read(buffer)) !=-1 ){
outStream.write(buffer,0, len);
}
byte[]data = outStream.toByteArray();//网页的二进制数据
outStream.close();
inStream.close();
returndata;
}
}