Android–網路通訊

來源:互聯網
上載者:User

一、擷取網路資源

用戶端代碼:

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();@Overridepublic 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 {@Overridepublic 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>

jsonvideo.jsp:

<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${jsonvideos}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.