android与web交互完整示例

首先建立一个简单的web工程,使用servlet技术:

下面是servlet的实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/** 
  * @FILE:ListServlet.java 
  * @AUTHOR:Administrator 
  * @DATE:2013-5-19 下午6:03:19 
  **/
package  com.yehui.servlet; 
    
import  java.io.IOException; 
import  java.io.PrintWriter; 
import  java.util.List; 
    
import  javax.servlet.ServletException; 
import  javax.servlet.http.HttpServlet; 
import  javax.servlet.http.HttpServletRequest; 
import  javax.servlet.http.HttpServletResponse; 
    
import  com.yehui.service.VideoNewsService; 
import  com.yehui.service.bean.News; 
import  com.yehui.service.impl.VideoNewsServiceImpl; 
    
/******************************************* 
  *  
  * @CLASS:ListServlet 
  * @DESCRIPTION: 
  * @AUTHOR:Administrator 
  * @VERSION:v1.0 
  * @DATE:2013-5-19 下午6:03:19 
  *******************************************/
public  class  ListServlet  extends  HttpServlet { 
     private  VideoNewsService service =  new VideoNewsServiceImpl(); 
    
     /** 
      * The doGet method of the servlet. <br> 
      *  
      * This method is called when a form has its tag value method equals to get. 
      *  
      * @param request 
      *            the request send by the client to the server 
      * @param response 
      *            the response send by the server to the client 
      * @throws ServletException 
      *             if an error occurred 
      * @throws IOException 
      *             if an error occurred 
      */
     public  void  doGet(HttpServletRequest request, HttpServletResponse response) 
             throws  ServletException, IOException { 
         doPost(request, response); 
    
    
    
     /** 
      * The doPost method of the servlet. <br> 
      *  
      * This method is called when a form has its tag value method equals to 
      * post. 
      *  
      * @param request 
      *            the request send by the client to the server 
      * @param response 
      *            the response send by the server to the client 
      * @throws ServletException 
      *             if an error occurred 
      * @throws IOException 
      *             if an error occurred 
      */
     public  void  doPost(HttpServletRequest request, HttpServletResponse response) 
             throws  ServletException, IOException { 
         List<News> videos = service.getLastNews(); 
         request.setAttribute( "videos" , videos); 
         // ("")里面是jsp的文件路径 
         request.getRequestDispatcher( "/WEB-INF/page/videonews.jsp" ).forward(request, response); 
    
    
}

web的service操作的bean:News:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/** 
  * @FILE:News.java 
  * @AUTHOR:Administrator 
  * @DATE:2013-5-19 下午6:08:00 
  **/
package  com.yehui.service.bean; 
    
/******************************************* 
  *  
  * @CLASS:News 
  * @DESCRIPTION: 
  * @AUTHOR:Administrator 
  * @VERSION:v1.0 
  * @DATE:2013-5-19 下午6:08:00 
  *******************************************/
public  class  News { 
     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; 
    
    
}

web的service接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** 
  * @FILE:VideoNewsService.java 
  * @AUTHOR:Administrator 
  * @DATE:2013-5-19 下午6:14:18 
  **/
package  com.yehui.service; 
    
import  java.util.List; 
    
import  com.yehui.service.bean.News; 
    
/******************************************* 
  *  
  * @CLASS:VideoNewsService 
  * @DESCRIPTION:     
  * @AUTHOR:Administrator 
  * @VERSION:v1.0 
  * @DATE:2013-5-19 下午6:14:18 
  *******************************************/
public  interface  VideoNewsService { 
    
     /**@description:获取最新的视频资讯    
      * @author:Administrator 
      * @return:List<News> 
      */
        
     public  List<News> getLastNews(); 
    
}

service的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/** 
  * @FILE:VideoNewsServiceImpl.java 
  * @AUTHOR:Administrator 
  * @DATE:2013-5-19 下午6:06:33 
  **/
package  com.yehui.service.impl; 
    
import  java.util.ArrayList; 
import  java.util.List; 
    
import  com.yehui.service.VideoNewsService; 
import  com.yehui.service.bean.News; 
    
/******************************************* 
  *  
  * @CLASS:VideoNewsServiceImpl 
  * @DESCRIPTION:     
  * @AUTHOR:Administrator 
  * @VERSION:v1.0 
  * @DATE:2013-5-19 下午6:06:33 
  *******************************************/
public  class  VideoNewsServiceImpl  implements  VideoNewsService { 
public  List<News> getLastNews(){ 
     List<News> newes= new  ArrayList<News>(); 
     newes.add( new  News( 1 , "喜洋洋" , 90 )); 
     newes.add( new  News( 2 , "灰太狼" , 30 )); 
     newes.add( new  News( 3 , "泷泽萝拉" , 10 )); 
     return  newes; 
}

jsp文件,这里注意是要返回xml的结果:所以文件的第一行必须加上<?xml version="1.0" encoding="UTF-8"?>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/** 
  * @FILE:VideoNewsServiceImpl.java 
  * @AUTHOR:Administrator 
  * @DATE:2013-5-19 下午6:06:33 
  **/
package  com.yehui.service.impl; 
    
import  java.util.ArrayList; 
import  java.util.List; 
    
import  com.yehui.service.VideoNewsService; 
import  com.yehui.service.bean.News; 
    
/******************************************* 
  *  
  * @CLASS:VideoNewsServiceImpl 
  * @DESCRIPTION:     
  * @AUTHOR:Administrator 
  * @VERSION:v1.0 
  * @DATE:2013-5-19 下午6:06:33 
  *******************************************/
public  class  VideoNewsServiceImpl  implements  VideoNewsService { 
public  List<News> getLastNews(){ 
     List<News> newes= new  ArrayList<News>(); 
     newes.add( new  News( 1 , "喜洋洋" , 90 )); 
     newes.add( new  News( 2 , "灰太狼" , 30 )); 
     newes.add( new  News( 3 , "泷泽萝拉" , 10 )); 
     return  newes; 
}

jsp文件,这里注意是要返回xml的结果:所以文件的第一行必须加上<?xml version="1.0" encoding="UTF-8"?>

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language= "java"  contentType= "text/xml; charset=UTF-8" import = "java.util.*"  pageEncoding= "utf-8" %><?xml version= "1.0" encoding= "UTF-8" ?> 
<%@ taglib prefix= "c"  uri= "http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix= "fmt"  uri= "http://java.sun.com/jsp/jstl/fmt" %> 
<%@ taglib prefix= "fn" uri= "http://java.sun.com/jsp/jstl/functions" %> 
<videonews > 
     <c:forEach items= "${videos}"  var= "video"  
     <news id= "${video.id}"
     <title>${video.title}</title> 
     <timelength>${video.timelength}</timelength> 
     </news> 
     </c:forEach> 
</videonews>

web.xml文件配置servlet:

  1. <?xml version="1.0" encoding="UTF-8"?>  

  2. <web-app version="3.0"  

  3.    xmlns="http://java.sun.com/xml/ns/javaee"  

  4.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

  5.    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  

  6.    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  

  7.  <display-name></display-name>  

  8.  <servlet>  

  9.    <description>This is the description of my J2EE component</description>  

  10.    <display-name>This is the display name of my J2EE component</display-name>  

  11.    <servlet-name>ListServlet</servlet-name>  

  12.    <servlet-class>com.yehui.servlet.ListServlet</servlet-class>  

  13.  </servlet>  

  14.  

  15.  <servlet-mapping>  

  16.    <servlet-name>ListServlet</servlet-name>  

  17.    <url-pattern>/ListServlet</url-pattern>  

  18.  </servlet-mapping>    

  19.  <welcome-file-list>  

  20.    <welcome-file>index.jsp</welcome-file>  

  21.  </welcome-file-list>  

  22. </web-app>  

好了,web服务器端已经构建成功。下面介绍android客户端:

依然为service操作的bean:

  1. /**  

  2. * @FILE:News.java  

  3. * @AUTHOR:Administrator  

  4. * @DATE:2013-5-19 下午6:08:00  

  5. **/  

  6. package com.yehui.bean;  

  7.  

  8. /*******************************************  

  9. *  

  10. * @CLASS:News  

  11. * @DESCRIPTION:  

  12. * @AUTHOR:Administrator  

  13. * @VERSION:v1.0  

  14. * @DATE:2013-5-19 下午6:08:00  

  15. *******************************************/  

  16. public class News {  

  17.    private Integer id;  

  18.    private String title;  

  19.    private Integer timelength;  

  20.  

  21.    public News() {  

  22.    }  

  23.  

  24.    public News(Integer id, String title, Integer timelength) {  

  25.        this.id = id;  

  26.        this.title = title;  

  27.        this.timelength = timelength;  

  28.    }  

  29.  

  30.    public Integer getId() {  

  31.        return id;  

  32.    }  

  33.  

  34.    public void setId(Integer id) {  

  35.        this.id = id;  

  36.    }  

  37.  

  38.    public String getTitle() {  

  39.        return title;  

  40.    }  

  41.  

  42.    public void setTitle(String title) {  

  43.        this.title = title;  

  44.    }  

  45.  

  46.    public Integer getTimelength() {  

  47.        return timelength;  

  48.    }  

  49.  

  50.    public void setTimelength(Integer timelength) {  

  51.        this.timelength = timelength;  

  52.    }  

  53.  

  54. }  

servece:通过pull技术对返回的xml文件内容进行解析:
  1. /**  

  2. * @FILE:VideoNewsService.java  

  3. * @AUTHOR:Administrator  

  4. * @DATE:2013-5-19 下午8:29:22  

  5. **/  

  6. package com.yehui.service;  

  7.  

  8. import java.io.IOException;  

  9. import java.io.InputStream;  

  10. import java.net.HttpURLConnection;  

  11. import java.net.URL;  

  12. import java.util.ArrayList;  

  13. import java.util.List;  

  14.  

  15. import org.xmlpull.v1.XmlPullParser;  

  16.  

  17.  

  18.  

  19. import android.util.Xml;  

  20.  

  21. import com.yehui.bean.News;  

  22.  

  23. /*******************************************  

  24. *  

  25. * @CLASS:VideoNewsService  

  26. * @DESCRIPTION:  

  27. * @AUTHOR:Administrator  

  28. * @VERSION:v1.0  

  29. * @DATE:2013-5-19 下午8:29:22  

  30. *******************************************/  

  31. public class VideoNewsService {  

  32.    public static List<News> getLastNews() throws Exception {  

  33.        List<News> newes = new ArrayList<News>();  

  34.        URL url = new URL("http://169.254.161.54:8888/web/ListServlet");  

  35.        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  

  36.        conn.setRequestMethod("GET");  

  37.        conn.setConnectTimeout(5000);  

  38.        conn.connect();  

  39.        if (conn.getResponseCode() == 200) {  

  40.            InputStream inputStream = conn.getInputStream();  

  41.            // 因为页面返回值是xml文件,所以现在就要解析这个xml,使用pull解析器解析  

  42.              

  43.            newesparseXML(inputStream);  

  44.  

  45.        }  

  46.        return newes;  

  47.    }  

  48.  

  49.    /**  

  50.     * @description:pull解析服务器返回xml文件  

  51.     * @author:Administrator  

  52.     * @return:List<News>  

  53.     * @param inputStream  

  54.     * @return  

  55.     * @throws XmlPullParserException  

  56.     * @throws IOException  

  57.     */  

  58.  

  59.    private static List<News> parseXML(InputStream inputStream)  

  60.            throws Exception {  

  61.        XmlPullParser xmlPullParser = Xml.newPullParser();  

  62.        xmlPullParser.setInput(inputStream, "utf-8");  

  63.        int event = xmlPullParser.getEventType();  

  64.        List<News> newes = new ArrayList<News>();  

  65.        News news = null;  

  66.        while (event != xmlPullParser.END_DOCUMENT) {  

  67.            switch (event) {  

  68.            case 2:  

  69.                if ("news".equals(xmlPullParser.getName())) {  

  70.                    int id = Integer  

  71.                            .valueOf(xmlPullParser.getAttributeValue(0));  

  72.                    news = new News();  

  73.                    news.setId(id);  

  74.                } else if ("title".equals(xmlPullParser.getName())) {  

  75.                    news.setTitle(xmlPullParser.nextText());  

  76.                } else if ("timelength".equals(xmlPullParser.getName())) {  

  77.                    news.setTimelength(Integer.valueOf(xmlPullParser.nextText()));  

  78.                }  

  79.                break;  

  80.            case 3:  

  81.                if ("news".equals(xmlPullParser.getName())) {  

  82.                    newes.add(news);  

  83.                    news = null;  

  84.                }  

  85.                break;  

  86.                default:  

  87.                    break;  

  88.                      

  89.            }  

  90.              

  91.            event = xmlPullParser.next();  

  92.        }  

  93.        return newes;  

  94.    }  

  95. }  

activity中使用线程调用service,从而更新UI
  1. package com.yehui.news;  

  2.  

  3. import java.util.ArrayList;  

  4. import java.util.HashMap;  

  5. import java.util.List;  

  6. import java.util.Map;  

  7.  

  8. import com.yehui.bean.News;  

  9. import com.yehui.service.VideoNewsService;  

  10.  

  11. import android.os.Bundle;  

  12. import android.os.Handler;  

  13. import android.os.Message;  

  14. import android.app.Activity;  

  15. import android.view.Menu;  

  16. import android.widget.ListView;  

  17. import android.widget.SimpleAdapter;  

  18. import android.widget.Toast;  

  19.  

  20. public class MainActivity extends Activity {  

  21.    ListView listview;  

  22.    private Handler handler = new Handler() {  

  23.          

  24.  

  25.        @Override  

  26.        public void handleMessage(Message msg) {  

  27.            try {  

  28.                List<News> newes = (List<News>) msg.obj;  

  29.  

  30.                List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  

  31.                for (News news : newes) {  

  32.                    HashMap<String, Object> item = new HashMap<String, Object>();  

  33.                    item.put("title", news.getTitle());  

  34.                    item.put("timelength", news.getTimelength());  

  35.                    data.add(item);  

  36.                }  

  37.                SimpleAdapter simpleAdapter = new SimpleAdapter(  

  38.                        getApplicationContext(), data, R.layout.item,  

  39.                        new String[] { "title", "timelength" }, new int[] {  

  40.                                R.id.title, R.id.timelength });  

  41.                listview.setAdapter(simpleAdapter);  

  42.            } catch (Exception e) {  

  43.                e.printStackTrace();  

  44.                Toast.makeText(getApplicationContext(), R.string.error, 1)  

  45.                        .show();  

  46.            }  

  47.        }  

  48.  

  49.    };  

  50.  

  51.    @Override  

  52.    protected void onCreate(Bundle savedInstanceState) {  

  53.        super.onCreate(savedInstanceState);  

  54.        setContentView(R.layout.activity_main);  

  55.        listview = (ListView) this.findViewById(R.id.listview);  

  56.        new Thread() {  

  57.  

  58.            @Override  

  59.            public void run() {  

  60.                List<News> newes;  

  61.                try {  

  62.                    newes = VideoNewsService.getLastNews();  

  63.                    Message msg = new Message();  

  64.                    msg.obj = newes;  

  65.                    handler.sendMessage(msg);  

  66.                } catch (Exception e) {  

  67.                    e.printStackTrace();  

  68.                }  

  69.  

  70.            }  

  71.  

  72.        }.start();  

  73.  

  74.    }  

  75.  

  76.    @Override  

  77.    public boolean onCreateOptionsMenu(Menu menu) {  

  78.        getMenuInflater().inflate(R.menu.main, menu);  

  79.        return true;  

  80.    }  

  81.  

  82. }  

layout文件,因为显示的时候用到了listview,所以这里对listview的行布局文件也列出

listview布局文件:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.    xmlns:tools="http://schemas.android.com/tools"  

  3.    android:layout_width="match_parent"  

  4.    android:layout_height="match_parent"  

  5.    android:orientation="vertical"  

  6.    android:paddingBottom="@dimen/activity_vertical_margin"  

  7.    android:paddingLeft="@dimen/activity_horizontal_margin"  

  8.    android:paddingRight="@dimen/activity_horizontal_margin"  

  9.    android:paddingTop="@dimen/activity_vertical_margin"  

  10.    tools:context=".MainActivity" >  

  11.  

  12.    <ListView  

  13.        android:id="@+id/listview"  

  14.        android:layout_width="fill_parent"  

  15.        android:layout_height="fill_parent" >  

  16.    </ListView>  

  17.  

  18. </LinearLayout>  

listview的行布局文件:
  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.    android:layout_width="match_parent"  

  4.    android:layout_height="match_parent"  

  5.    android:orientation="horizontal" >  

  6.  

  7.    <TextView  

  8.        android:id="@+id/title"  

  9.        android:layout_width="fill_parent"  

  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>  

最后将访问网络的权限加入到清单文件中:

<uses-permission android:name="android.permission.INTERNET"/>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值