Android应用开发之获取web服务器xml数据


实验步骤:

1、 配置J2EE开发环境,并部署web应用viderweb,启动服务

2、 打开浏览器访问网址

http://localhost:8080/videoweb/video/list.do

演示xml数据

3、 创建Android客户端工程,实现访问上面的网址并且将取得的xml数据进行解析并显示,如下图:


Android客户端代码

程序流程

 

资源

  1. <resources>  
  2.     <string name="app_name">视频资讯客户端</string>  
  3.     <string name="error">网络连接失败</string>  
  4. </resources>  

布局

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.    
  7.     <ListView  
  8.         android:id="@+id/listView"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent" />  
  11.    
  12. </LinearLayout>  

item.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="horizontal" >  
  6.    
  7.     <TextView  
  8.         android:id="@+id/title"  
  9.         android:layout_width="250dip"  
  10.         android:layout_height="wrap_content" />  
  11.    
  12.     <TextView  
  13.         android:id="@+id/timelength"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content" />  
  16.    
  17. </LinearLayout>  

添加业务bean类Video

  1. package cn.class3g.domain;  
  2.    
  3. public class Video {  
  4.     private Integer id;  
  5.     private String title;  
  6.     private Integer timelength;  
  7.    
  8.     public Video(Integer id, String title, Integer timelength) {  
  9.        super();  
  10.        this.id = id;  
  11.        this.title = title;  
  12.        this.timelength = timelength;  
  13.     }  
  14.     public Video() {  }  
  15.     public Integer getId() {  
  16.        return id;  
  17.     }  
  18.     public void setId(Integer id) {  
  19.        this.id = id;  
  20.     }  
  21.     public String getTitle() {  
  22.        return title;  
  23.     }  
  24.     public void setTitle(String title) {  
  25.        this.title = title;  
  26.     }  
  27.     public Integer getTimelength() {  
  28.        return timelength;  
  29.     }  
  30.     public void setTimelength(Integer timelength) {  
  31.        this.timelength = timelength;  
  32.     }  
  33.     public String toString() {  
  34.        return "Video [id=" + id + "title=" + title + "timelength="  
  35.               + timelength + "]";  
  36.     }  
  37. }  

添加业务类VideoService类

  1. package cn.class3g.service;  
  2. ...  
  3. public class VideoService {  
  4.    
  5.     /**  
  6.      * 从服务器获取最新的视频资讯  
  7.      *  
  8.      * @return  
  9.      * @throws Throwable  
  10.      */  
  11.     public static List<Video> getLastVideos() throws Throwable {  
  12.        String path =  
  13. "http://192.168.1.102:8080/videoweb/video/list.do";//  
  14. 实验环境中使用pc的ip,不能用localhost或127.0.0.1  
  15.        URL url = new URL(path);  
  16.        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  17.        conn.setConnectTimeout(5 * 1000);  
  18.        conn.setRequestMethod("GET");  
  19.        InputStream inStream = conn.getInputStream();  
  20.        return parseXML(inStream);  
  21.     }  
  22.    
  23.     private static List<Video> parseXML(InputStream inStream) throws Exception {  
  24.        Video video = null;  
  25.        List<Video> videos = null;  
  26.        XmlPullParser pullParser = Xml.newPullParser();  
  27.        pullParser.setInput(inStream, "UTF-8");  
  28.         
  29.        int event = pullParser.getEventType();// 触发第一个事件  
  30.         
  31.        while (event != XmlPullParser.END_DOCUMENT) {  
  32.            switch (event) {  
  33.            case XmlPullParser.START_DOCUMENT:  
  34.               videos = new ArrayList<Video>();  
  35.               break;  
  36.            case XmlPullParser.START_TAG:  
  37.               if ("video".equals(pullParser.getName())) {  
  38.                   int id = new Integer(pullParser.getAttributeValue(0));  
  39.                   video = new Video();  
  40.                   video.setId(id);  
  41.               }  
  42.               if (video != null) {  
  43.                   if ("title".equals(pullParser.getName())) {  
  44.                      video.setTitle(pullParser.nextText());  
  45.                   }  
  46.                   if ("timelength".equals(pullParser.getName())) {  
  47.                      video.setTimelength(new Integer(pullParser.nextText()));  
  48.                   }  
  49.               }  
  50.               break;  
  51.    
  52.            case XmlPullParser.END_TAG:  
  53.               if ("video".equals(pullParser.getName())) {  
  54.                   videos.add(video);  
  55.                   video = null;  
  56.               }  
  57.               break;  
  58.            }  
  59.            event = pullParser.next();  
  60.        }  
  61.        return videos;  
  62.     }  
  63. }  
Activity类MyVideoNewsActivity
  1. public class MyVideoNewsActivity extends Activity {  
  2.    
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.main);  
  6.          
  7.         try {  
  8.            List<Video> videos = VideoService.getLastVideos();//获取最新视频资讯  
  9.            ListView listView = (ListView)this.findViewById(R.id.listView);  
  10.            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();  
  11.            for(Video video : videos){  
  12.               HashMap<String, Object> item = new HashMap<String, Object>();  
  13.               item.put("title", video.getTitle());  
  14.               item.put("timelength", "时长:"+video.getTimelength());  
  15.               item.put("id", video.getId());  
  16.               data.add(item);  
  17.            }  
  18.            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,  
  19.                   new String[]{"title","timelength"}, new int[]{R.id.title, R.id.timelength});  
  20.            listView.setAdapter(adapter);  
  21.        } catch (Throwable e) {  
  22.            Log.e("TAG", e.toString());  
  23.            Toast.makeText(this, R.string.error, 1).show();  
  24.        }     
  25.     }  
  26. }  
Androd中获取网页代码

布局

  1. <Button  
  2.        android:layout_width="fill_parent"  
  3.        android:layout_height="wrap_content"  
  4.        android:text="@string/btn_text"  
  5.        android:id="@+id/showBtn"  
  6.        />  
  7.     
  8.    <ImageView  
  9.        android:layout_width="wrap_content"  
  10.        android:layout_height="wrap_content"  
  11.        android:id="@+id/imageView"  
  12.        />    
代码:在前面的ImageService.getImage()方法基础上修改即可

HtmlService

  1. public class HtmlService {  
  2.     /**  
  3.      * 获取给定路径的html代码  
  4.      * @param path 网页路径  
  5.      * @return  
  6.      * @throws Exception  
  7.      */  
  8.     public static String getHtml(String path) throws Exception{  
  9.        URL url = new URL(path);  
  10.        //get //post  
  11.        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  12.        conn.setRequestMethod("GET");  
  13.        conn.setConnectTimeout(5*1000);  
  14.        InputStream inStream = conn.getInputStream();  
  15.         
  16.        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  17.        byte[] buffer = new byte[1024];  
  18.        int len = 0;  
  19.        while( (len = inStream.read(buffer)) !=-1 ){  
  20.            outStream.write(buffer, 0, len);  
  21.        }  
  22.        byte[] data = outStream.toByteArray();//网页的二进制数据  
  23.        outStream.close();  
  24.        inStream.close();  
  25.        return new String(data, "gb2312");  
  26.     }  
  27. }  
ShowHtmlActivity
  1. public void onClick(View v) {  
  2.     String path = pathText.getText().toString();  
  3.     try {  
  4.        String htmlcode = HtmlService.getHtml(path);  
  5.        resultView.setText(htmlcode);  
  6.     } catch (Exception e) {  
  7.        Log.e(TAG, e.toString());  
  8.        Toast.makeText(ShowHtmlActivity.this, R.string.error, 1).show();  
  9.     }  
  10. }  

相关内容