一、获取网络资源
客户端代码:
package com.net.demo.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log; import com.net.demo.domain.Video; import com.net.demo.util.AppConstant; import com.net.demo.util.NetUtil; public class NetService { private static final int TIMEOUT = 5000; /** * 获取网络资源的二进制数据 * @param urlStr * @return * @throws Exception */ public byte[] getData(String urlStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setConnectTimeout(TIMEOUT); InputStream inStream = httpConnection.getInputStream(); return NetUtil.readDataFromInputStream(inStream); } /** * 从网络获取xml文件并解析 * @param urlStr * @return * @throws Exception */ public List<Video> getLastVideosFromXML(String urlStr) throws Exception { HttpURLConnection conn = (HttpURLConnection) getURLConnection(urlStr); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); return parseXml(inStream, "UTF-8"); } /** * 从网络获取json数据并解析 * @param urlStr * @return * @throws Exception */ public List<Video> getLastVideosFromJSON(String urlStr) throws Exception { HttpURLConnection conn = (HttpURLConnection) getURLConnection(urlStr); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); byte[] data = NetUtil.readDataFromInputStream(inStream); String jsonStr = new String(data); Log.d(AppConstant.TAG, jsonStr); return parseJSON(jsonStr); } private URLConnection getURLConnection(String urlStr) throws Exception { URL url = new URL(urlStr); return url.openConnection(); } private List<Video> parseXml(InputStream inStream, String enc) throws Exception { List<Video> videos = null; Video video = null; XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(inStream, enc); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: videos = new ArrayList<Video>(); break; case XmlPullParser.START_TAG: String tagName = parser.getName(); if ("video".equals(tagName)) { video = new Video(); video.setId(Integer.valueOf(parser.getAttributeValue(0))); } if (video != null) { if ("title".equals(tagName)) { video.setTitle(parser.nextText()); } if ("timelength".equals(tagName)) { video.setTime(Integer.valueOf(parser.nextText())); } } break; case XmlPullParser.END_TAG: if ("video".equals(parser.getName())) { videos.add(video); video = null; } break; } eventType = parser.next(); } return videos; } private List<Video> parseJSON(String jsonData) throws Exception { List<Video> videos = new ArrayList<Video>(); JSONArray jsonArray = new JSONArray(jsonData); int len = jsonArray.length(); for (int i = 0; i < len; i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); int id = jsonObj.getInt("id"); String title = jsonObj.getString("title"); int timelength = jsonObj.getInt("timelength"); videos.add(new Video(id, title, timelength)); } return videos; } }测试类:
package com.net.demo; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.net.demo.domain.Video; import com.net.demo.service.NetService; import com.net.demo.util.AppConstant; public class NetTest extends AndroidTestCase { public void testGetData() throws Throwable { NetService nService = new NetService(); byte[] data = nService.getData("http://www.tuswallpapersgratis.com/images/wallpapers/corazon_de_fuego-1024x768-250510.jpeg"); Log.d(AppConstant.TAG, "数据的大小:" + data.length); } public void testPullParser() throws Throwable { String urlStr = "http://192.168.1.2:8080/videoweb/video/list.do?format=xml"; NetService nService = new NetService(); List<Video> videos = nService.getLastVideosFromXML(urlStr); for (Video video : videos) { Log.d(AppConstant.TAG, video.toString()); } } public void testJsonParser() throws Throwable { String urlStr = "http://192.168.1.2:8080/videoweb/video/list.do?format=json"; NetService nService = new NetService(); List<Video> videos = nService.getLastVideosFromJSON(urlStr); for (Video video : videos) { Log.d(AppConstant.TAG, video.toString()); } } }服务器端代码
package com.demo.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.demo.domain.Video; import com.demo.formbean.VideoForm; import com.demo.service.VideoService; import com.demo.service.impl.VideoServiceBean; public class VideoListAction extends Action { private VideoService service = new VideoServiceBean(); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { VideoForm videoForm = (VideoForm) form; String format = videoForm.getFormat(); List<Video> videos = service.getlastVideos(); if ("xml".equals(format)) { request.setAttribute("xmlvideos", videos); return mapping.findForward("xmlvideo"); } else if ("json".equals(format)) { StringBuilder sb = new StringBuilder(); sb.append('['); for (Video video : videos) { sb.append('{'); sb.append("id").append(':').append(video.getId()).append(','); sb.append("title").append(':').append(video.getTitle()).append(','); sb.append("timelength").append(':').append(video.getTime()); sb.append('}'); sb.append(','); } sb.deleteCharAt(sb.length() - 1); sb.append(']'); request.setAttribute("jsonvideos", sb.toString()); return mapping.findForward("jsonvideo"); } else { request.setAttribute("xmlvideos", videos); return mapping.findForward("xmlvideo"); } } }
package com.demo.service.impl; import java.util.ArrayList; import java.util.List; import com.demo.domain.Video; import com.demo.service.VideoService; public class VideoServiceBean implements VideoService { @Override public List<Video> getlastVideos() throws Exception { List<Video> videos = new ArrayList<Video>(); videos.add(new Video(11, "aa", 70)); videos.add(new Video(12, "bb", 80)); videos.add(new Video(13, "cc", 90)); System.out.println(videos.toString()); return videos; } }xmlvideo.jsp:
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %><?xml version="1.0" encoding="UTF-8"?> <videos> <c:forEach items="${xmlvideos}" var="video"> <video id="${video.id }"> <title>${video.title }</title> <timelength>${video.time }</timelength> </video> </c:forEach> </videos>
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${jsonvideos}