packageygc.yxb.service;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.ArrayList;importjava.util.List;importorg.json.JSONArray;importorg.json.JSONObject;importorg.xmlpull.v1.XmlPullParser;importandroid.util.Xml;importygc.yxb.domain.News;importygc.yxb.utils.StreamTool;public classVideoNewsService {/*** 获取最新的视频资讯接受服务器端XML格式的数据
*@return*@throwsException*/
public static List getLastNews() throwsException{
String path="http://192.168.1.113:8080/videonews/ListServlet";
URL url= newURL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();returnparseXML(inStream);
}return null;
}/*** 获取最新的视频资讯 接受服务器端JSON格式的数据
*@return*@throwsException*/
public static List getJSONLastNews() throwsException{
String path="http://192.168.1.113:8080/videonews/ListServlet?format=json";
URL url= newURL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();returnparseJSON(inStream);
}return null;
}/*** 解析JSON数据
*@paraminStream
*@return
*/
private static List parseJSON(InputStream inStream) throwsException {
List newses = new ArrayList();byte[] data =StreamTool.read(inStream);//将字节数组转换成字符串
String json= newString(data);//将json对象转换成json的数组对象
JSONArray array = newJSONArray(json);for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject=array.getJSONObject(i);
News news=new News(jsonObject.getInt("id"),jsonObject.getString("title"),jsonObject.getInt("timelength"));
newses.add(news);
}returnnewses;
}/*** 解析服务器返回的XML数据
*@paraminStream
*@return
*/
private static List parseXML(InputStream inStream) throwsException{
List newses = new ArrayList();
News news= null;//用Pull解析器解析XML文件
XmlPullParser parser=Xml.newPullParser();
parser.setInput(inStream,"UTF-8");//得到开始文档XML事件
int event =parser.getEventType();//不等于结束事件,循环读取XML文件并封装成对象
while(event !=XmlPullParser.END_DOCUMENT){switch(event) {caseXmlPullParser.START_TAG:if("news".equals(parser.getName())){int id = new Integer(parser.getAttributeValue(0));
news= newNews();
news.setId(id);
}else if("title".equals(parser.getName())){
news.setTitle(parser.nextText());
}else if("timelength".equals(parser.getName())){
news.setTimelenght(newInteger(parser.nextText()));
}break;caseXmlPullParser.END_TAG:if("news".equals(parser.getName())){
newses.add(news);
news= null;
}break;
}
event=parser.next();
}returnnewses;
}
}