在网络上获取XML显示在手机上

来源:互联网 发布:马克思 知乎 编辑:程序博客网 时间:2024/04/28 00:59
(1)新建一个动态web工程
(a)创建实例对象代码如下:
package cn.itcast.domain;
public class News {           //Java并
private Integer id;
private String title;
private Integer timelength;
public News(){}
public News(Integer id, String title, Integer timelength) {     //为添加数据方便,为其添加一个构造器
this.id = id;
this.title = title;
this.timelength = timelength;
}
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 getTimelength() {
return timelength;
}
public void setTimelength(Integer timelength) {
this.timelength = timelength;
}
}
 (b)创建一个servlet文件,代码如下:
package cn.itcast.service.impl;
public class VideoNewsServiceBean implements VideoNewsService {         //业务并
public List<News> getLastNews(){
List<News> newses = new ArrayList<News>();
newses.add(new News(35, "喜羊羊与灰太狼全集",90));
newses.add(new News(12, "老张与灰太狼",20));
newses.add(new News(56, "老方与LILI",30));
return newses;
}
}
/*
 * 在做Java EE应该面向接口编程,就应抽取一个接口来
 */
接口:
package cn.itcast.service;
public interface VideoNewsService {     //接口
/**
* 获取最新视频资讯
* @return
*/
public List<News> getLastNews();


}
       在dopost方法中写入:
package cn.itcast.servlet;
public class ListServlet extends HttpServlet {
private static final long serialVersionUID=1L; 

private VideoNewsService service = new VideoNewsServiceBean();   //定义一个成员变量,把业务并建立出来

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<News> videos = service.getLastNews();    //得到最新的视频资讯
request.setAttribute("videos", videos);
request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response); //将请求内部转发给jsp
//response.setContentType("/WEB-INF/page/videonews.jsp");
}
}
写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"?>
<videonews><c:forEach items="${videos}" var="video">
<news id="${video.id}">
<title>${video.title}</title>
<timelength>${video.timelength}</timelength>
</news></c:forEach>
</videonews>
(2)android代码:
package com.example.domain;
public class News {           //Java并
private Integer id;
private String title;
private Integer timelength;
public News(){}
public News(Integer id, String title, Integer timelength) {     //为添加数据方便,为其添加一个构造器
this.id = id;
this.title = title;
this.timelength = timelength;
}
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 getTimelength() {
return timelength;
}
public void setTimelength(Integer timelength) {
this.timelength = timelength;
}
}


package com.example.news;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ListView listView = (ListView) this.findViewById(R.id.listView);  
        try {
List<News> videos = VideoNewsService.getLastNews();
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
//访问VideoNewsService,取得最新的视频资讯
for(News news : videos){
   HashMap<String, Object> item =new HashMap<String, Object>();
item.put("id", news.getId());
item.put("title", news.getTitle());
item.put("timelength", news.getTimelength());
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);   //将适配器传给listView对象
} catch (Exception e) {
e.printStackTrace();
}   
    }
}
}


package com.example.service;
/**
 * 业务并,专门用于从web应用中得到他所返回的XML数据
 * @author Administrator
 */
public class VideoNewsService {
/**
* 获取最新的视频资讯
* @return
* @throws Exception
*/
public static List<News> getLastNews() throws Exception{    //业务方法用于存放获得的最新资讯
String path="http://192.168.1.100:8080/videonews/ListServlet";  //确定路径
URL url = new URL(path);     //把路径封装成URL对象
HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();  //打开http协议的connection对象
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream();   //得到输入流
return parseXml(inStream);    //解析XML
}
return null;

}
    /**
     * 解析服务器返回的XML数据
     * <?xml version="1.0" encoding="UTF-8"?>
<videonews>
<news id="35">
<title>喜羊羊与灰太狼全集</title>
<timelength>90</timelength>
</news>
<news id="12">
<title>老张与灰太狼</title>
<timelength>20</timelength>
</news>
<news id="35">
<title>老方与LILI</title>
<timelength>30</timelength>
</news>
</videonews>
     * @param inStream
     * @return
     */
private static List<News> parseXml(InputStream inStream) throws Exception{
List<News> newses = new ArrayList<News>();
News news = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream,"UTF-8");
int event = parser.getEventType();   //得到开始文档事件
while(event!=XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_TAG:
if("news".equals(parser.getName())){     //判断是否为news
int id = new Integer(parser.getAttributeValue(0));
news = new News();
news.setId(id);
}else if("title".equals(parser.getName())){     //判断是否为title
news.setTitle(parser.nextText());
}else if("timelength".equals(parser.getName())){     //判断是否为title
news.setTimelength(new Integer(parser.nextText()));
}
break;
case XmlPullParser.END_TAG:
if("news".equals(parser.getName())){ 
newses.add(news);
news = null;
}
break;
}
event = parser.next();
}
return newses;
}
}

布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <ListVIew
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView" 
        />
</RelativeLayout>


<?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="match_parent"
    android:orientation="horizontal" 
    >
<TextView 
    android:layout_width="230dp"
    android:layout_height="match_parent"
    android:id="@+id/title"
    />    
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:id="@+id/timelength"
    />    
</LinearLayout>


 <!-- 访问网络权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
0 0
原创粉丝点击