First, write a JSP program on the application server and use JSP and Servlet for simple implementation, as shown in
package cn.roco.domain;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;}}
Package CN. roco. service; import Java. util. list; import CN. roco. domain. news; public interface videonewsservice {/*** get the latest video information * @ return */public list <News> getlastnews ();}
Package CN. roco. service. impl; import Java. util. arraylist; import Java. util. list; import CN. roco. domain. news; import CN. roco. service. videonewsservice; public class videonewsservicebean implements videonewsservice {/*** simulate retrieving data from the server and returning */public list <News> getlastnews () {list <News> newses = new arraylist <News> (); For (INT I = 1; I <30; I ++) {newses. add (new news (I, "mongoi" + I, I + 90) ;}return newses ;}}
Package CN. roco. 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 CN. roco. domain. news; import CN. roco. service. videonewsservice; import CN. roco. service. impl. videonewsservicebean; public class listservlet extends httpservlet {private videonewsservice newsservice = new videonewsservicebean (); protected void doget (Response req, response resp) throws handle, ioexception {list <News> videos = newsservice. getlastnews (); string format = req. getparameter ("format"); // return the JSON format if ("JSON ". equals (Format) {stringbuilder builder = new stringbuilder (); builder. append ('['); For (News news: videos) {builder. append ('{'); builder. append ("ID :"). append (News. GETID ()). append (','); // escape "" Double quotation mark builder. append ("title :\""). append (News. gettitle ()). append ("\", "); builder. append ("timelength :"). append (News. gettimelength (); builder. append ("},");} builder. deletecharat (builder. length ()-1); // remove the final ', 'builder. append (']'); req. setattribute ("JSON", builder. tostring (); req. getrequestdispatcher ("/WEB-INF/page/jsonvideonews. JSP "). forward (req, resp);} else {// return XML format req. setattribute ("videos", videos); req. getrequestdispatcher ("/WEB-INF/page/videonews. JSP "). forward (req, resp) ;}} protected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {doget (req, resp );}}
If you want to return the XML file, forward to the videonews. jsp page.
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><?xml version="1.0" encoding="UTF-8"?><videonews> <c:forEach items="${videos}" var="video"><news id="${video.id}"><title>${video.title}</title><timelength>${video.timelength}</timelength> </news></c:forEach> </videonews>
If you want to return the XML file, forward to the videonews. jsp page. If you want to return the JSON file, forward to the jsonvideonews. jsp page.
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
Web. xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ListServlet</servlet-name> <servlet-class>cn.roco.servlet.ListServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ListServlet</servlet-name> <url-pattern>/ListServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
Write the Android app on the server
Shows the architecture:
package cn.roco.news.domain;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;}}
Package CN. roco. utils; import Java. io. bytearrayoutputstream; import Java. io. inputstream; public class stremtools {/*** read data from the input stream * @ Param inputstream input stream * @ return binary stream data * @ throws exception */public static byte [] Read (inputstream) throws exception {bytearrayoutputstream outputstream = new bytearrayoutputstream (); byte [] buffer = new byte [1024]; int length = 0; while (length = inputstream. read (buff Er ))! =-1) {outputstream. Write (buffer, 0, length);} inputstream. Close (); Return outputstream. tobytearray ();}}
Package CN. roco. news. 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 CN. roco. news. domain. news; import CN. roco. utils. stremtools; public class videonewsservice {/*** get the latest video information * In JSON format * @ para M path * @ return * @ throws exception */public static list <News> getjsonlastnews (string path) throws exception {URL url = new URL (PATH); httpurlconnection connection = (httpurlconnection) URL. openconnection (); // connection object based on HTTP protocol. setconnecttimeout (5000); connection. setrequestmethod ("get"); If (connection. getresponsecode () == 200) {inputstream = connection. getinputstream (); Return parse JSON (inputstream);} else {Throw new runtimeexception ("server response failed ");}} /*** parse the JSON data returned by the server ** @ Param inputstream * @ return * @ throws exception */Private Static list <News> parsejson (inputstream) throws exception {list <News> newses = new arraylist <News> (); byte [] DATA = stremtools. read (inputstream); string jsondata = new string (data, "UTF-8"); jsonarray array = new jsonarray (jsondata); For (INT I = 0; I <Array. length (); I ++) {jsonobject = array. getjsonobject (I); news = new news (jsonobject. getint ("ID"), jsonobject. getstring ("title"), jsonobject. getint ("timelength"); newses. add (News);} return newses ;} /*** get the latest video information * in XML format * @ Param path * @ return * @ throws exception */public static list <News> getlastnews (string path) throws exception {URL url = new URL (PATH); httpurlconnection Conn Ection = (httpurlconnection) URL. openconnection (); // connection object based on HTTP protocol. setconnecttimeout (5000); connection. setrequestmethod ("get"); If (connection. getresponsecode () == 200) {inputstream = connection. getinputstream (); Return parsexml (inputstream);} return NULL ;} /*** parse the XML data returned by the server ** @ Param inputstream * @ return */Private Static list <News> parsexml (inputstream) throws exce Ption {list <News> newses = new arraylist <News> (); news = NULL; xmlpullparser parser = xml. newpullparser (); parser. setinput (inputstream, "UTF-8"); int event = parser. geteventtype (); 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. settimelength (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 ;}}
Package CN. roco. news; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import CN. roco. news. domain. news; import CN. roco. news. service. videonewsservice; import android. app. activity; import android. OS. bundle; import android. widget. listview; import android. widget. simpleadapter; import android. widget. toast; public class mainactivity extends activity {/** called when the activity is first Created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); listview = (listview) findviewbyid (R. id. listview); try {// use XML format // string xmlpath = "http: // 192.168.15.58: 8080/Hello/listservlet"; // list <News> videos = videonewsservice. getlastnews (); // use the JSON Format String jsonpath = "http: // 192.168.15.58: 8080/Hello/listservlet? Format = JSON "; List <News> videos = videonewsservice. getjsonlastnews (jsonpath); List
Item. xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:id="@+id/title" android:layout_width="200dp"android:layout_height="wrap_content"/><TextView android:id="@+id/timelength" android:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>
Main. xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayout android:orientation="horizontal"android:layout_width="wrap_content" android:layout_height="wrap_content"><TextView android:text="@string/title" android:layout_width="200dp"android:layout_height="wrap_content" /><TextView android:text="@string/details" android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout><ListView android:layout_width="fill_parent"android:layout_height="wrap_content" android:id="@+id/listView" /></LinearLayout>
String. xml
<? XML version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Hello world, mainactivity! </String> <string name = "app_name"> video information </string> <string name = "timelength"> duration: </string> <string name = "min"> minute </string> <string name = "title"> title </string> <string name = "details"> details </string> </resources>
<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "CN. roco. news "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 8 "/> <! -- Access Internet permissions --> <uses-Permission Android: Name = "android. permission. internet "/> <application Android: icon =" @ drawable/icon "Android: Label =" @ string/app_name "> <activity Android: Name = ". mainactivity "Android: Label =" @ string/app_name "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> </Application> </manifest>
Running effect: