例子说明:用户通过访问web资源的最新电影资讯,服务器端生成XML或JSON格式数据,返回Android客户端进行显示。
此案例开发需要两个方面 WEB开发和android开发.
一.web开发相对比较简单,只是模拟一下
相关代码如下:
1.实体Bean
package ygc.yxb.domain; /** * 电影资讯实体Bean * @author YXB * */ public class News { private Integer id; //id private String title; //电影名称 private Integer timelenght; //时长 public News() { } public News(Integer id, String title, Integer timelenght) { this.id = id; this.title = title; this.timelenght = timelenght; } 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 getTimelenght() { return timelenght; } public void setTimelenght(Integer timelenght) { this.timelenght = timelenght; } }
2.业务逻辑
package ygc.yxb.service.impl; import java.util.ArrayList; import java.util.List; import ygc.yxb.domain.News; import ygc.yxb.service.VideoNewsService; public class VideoNewsServiceImpl implements VideoNewsService { /** * 获取电影资讯的业务方法 */ public List<News> getLastNews(){ List<News> newses = new ArrayList<News>(); newses.add(new News(32, "大话西游", 90)); newses.add(new News(12, "轩辕剑", 40)); newses.add(new News(56, "爱情公寓", 30)); return newses; } }
3.Servlet
package ygc.yxb.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ygc.yxb.domain.News; import ygc.yxb.service.VideoNewsService; import ygc.yxb.service.impl.VideoNewsServiceImpl; /** * 用最原始的web开发servlet请求服务器,并返回客户端数据 */ public class ListServlet extends HttpServlet { private static final long serialVersionUID = 1L; private VideoNewsService service = new VideoNewsServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<News> videos = service.getLastNews(); String format=request.getParameter("format"); //如果用户请求的是这个路径,则返回JSON格式的数据.http://192.168.1.113:8080/videonews/ListServlet?format=json if("json".equals(format)){ //[{id:56,title:"xxxx",timelength:90}] //组拼一个JSON格式的对象 StringBuilder builder = new StringBuilder(); builder.append('['); for (News news : videos) { builder.append('{'); builder.append("id:").append(news.getId()).append(','); builder.append("title:\"").append(news.getTitle()).append("\","); builder.append("timelength:").append(news.getTimelenght()); builder.append("},"); } builder.deleteCharAt(builder.length()-1); builder.append(']'); request.setAttribute("json", builder.toString()); request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response); //如果用户请求的是这个路径,则返回XML格式的数据.http://192.168.1.113:8080/videonews/ListServlet }else{ request.setAttribute("videos", videos); request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response); } } }
4.jsp页面
4.1.jsonvideonews.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
4.2.videonews.jsp XML数据
<%@ 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.timelenght}</timelength> </news> </c:forEach> </videonews>
到此为止web开发完毕,现在Android开发相关代码
1.实体Bean
package ygc.yxb.domain; public class News { private Integer id; private String title; private Integer timelenght; public News() { } public News(Integer id, String title, Integer timelenght) { this.id = id; this.title = title; this.timelenght = timelenght; } 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 getTimelenght() { return timelenght; } public void setTimelenght(Integer timelenght) { this.timelenght = timelenght; } }
2.业务逻辑
package ygc.yxb.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 ygc.yxb.domain.News; import ygc.yxb.utils.StreamTool; public class VideoNewsService { /** * 获取最新的视频资讯接受服务器端XML格式的数据 * @return * @throws Exception */ public static List<News> getLastNews() throws Exception{ String path="http://192.168.1.113:8080/videonews/ListServlet"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); return parseXML(inStream); } return null; } /** * 获取最新的视频资讯 接受服务器端JSON格式的数据 * @return * @throws Exception */ public static List<News> getJSONLastNews() throws Exception{ String path="http://192.168.1.113:8080/videonews/ListServlet?format=json"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); return parseJSON(inStream); } return null; } /** * 解析JSON数据 * @param inStream * @return */ private static List<News> parseJSON(InputStream inStream) throws Exception { List<News> newses = new ArrayList<News>(); byte[] data =StreamTool.read(inStream); //将字节数组转换成字符串 String json= new String(data); //将json对象转换成json的数组对象 JSONArray array = new JSONArray(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); } return newses; } /** * 解析服务器返回的XML数据 * @param inStream * @return */ private static List<News> parseXML(InputStream inStream) throws Exception{ List<News> newses = new ArrayList<News>(); 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) { case XmlPullParser.START_TAG: if("news".equals(parser.getName())){ int id = new Integer(parser.getAttributeValue(0)); news = new News(); news.setId(id); }else if("title".equals(parser.getName())){ news.setTitle(parser.nextText()); }else if("timelength".equals(parser.getName())){ news.setTimelenght(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; } }
3.Activity
package ygc.yxb.news; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import ygc.yxb.domain.News; import ygc.yxb.service.VideoNewsService; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView listView=(ListView)this.findViewById(R.id.listView); try { List<News> videos=VideoNewsService.getJSONLastNews(); List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>(); 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", getResources().getString(R.string.timelength)+ news.getTimelenght()+getResources().getString(R.string.min)); data.add(item); } //用SimpleAdapter 绑定ListView控件 SimpleAdapter adapter = new SimpleAdapter(this,data, R.layout.item,new String[]{"title","timelength"}, new int[]{R.id.title,R.id.timelength}); listView.setAdapter(adapter); } catch (Exception e) { e.printStackTrace(); } } }
4读取数据流工具类:
package ygc.yxb.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { /** * 读取流中的数据 * @param inStream * @return * @throws Exception */ public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; //如果字节流中的数据不等于-1,就说明一直有,然后循环读出 while( (len=inStream.read(buffer)) !=-1){ //将读出的数据放入内存中 outputStream.write(buffer); } inStream.close(); return outputStream.toByteArray(); } }
这里android 开发完毕,而显示的控件是ListView 最后在清单文件中,配置访问网络的权限即可。
运行效果如下: