Android Network Programming: obtaining XML on the network, android Network Programming

Source: Internet
Author: User

Android Network Programming: obtaining XML on the network, android Network Programming

Android Network Programming: Retrieving XML on the network


Please respect others' labor achievements, repost the Source: Android Network Programming to get XML on the network

To obtain XML on the network, the server must provide support.

1. Create a server:

Server project structure:


Server run:


Step 1: Create the JavaBean required by the business

 

Package com. jph. server. model; import java. util. date;/**** News entity class * @ author jph * Date: 2014.09.26 */public class News {private Integer id; private String title; private Date publishDate; public News (Integer id, String title, Date publishDate) {this. id = id; this. title = title; this. publishDate = publishDate;} 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 Date getPublishDate () {return publishDate;} public void setPublishDate (Date publishDate) {this. publishDate = publishDate ;}}

Step 2: create business logic interfaces and specific implementation classes

Business interface:

 

Package com. jph. server. service; import java. util. list; import com. jph. server. model. news; public interface XMLService {/*** get the latest information * @ return */public List <News> getLastNews ();}

Business interface implementation class:

 

Package com. jph. server. service. impl; import java. util. arrayList; import java. util. date; import java. util. list; import com. jph. server. model. news; import com. jph. server. service. XMLService; public class XMLServiceBean implements XMLService {/*** get the latest video information * @ return */public List <News> getLastNews () {List <News> newes = new ArrayList <News> (); newes. add (new News (1, "jph", new Date (System. currentTimeMillis () + 100002); newes. add (new News (2, "admin", new Date (System. currentTimeMillis () + 330002); newes. add (new News (3, "tom", new Date (System. currentTimeMillis () + 180002); return newes ;}}

Step 3: Create a controller Servlet

 

Package com. jph. server. xml; 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 com. jph. server. model. news; import com. jph. server. service. XMLService; import com. jph. server. service. impl. XMLServiceBean;/*** responds to client requests: http: // xxx/ServerForXML/ServletForXMLServlet */public class ServletForXML extends HttpServlet {private static final long serialVersionUID = 1L; private XMLService newsService = new XMLServiceBean (); protected void doGet (HttpServletRequest request, incluresponse) throws ServletException, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {List <News> newes = newsService. getLastNews (); // get the latest video information request. setAttribute ("newes", newes); // redirects client requests to news. jsp page request. getRequestDispatcher ("/WEB-INF/page/news. jsp "). forward (request, response );}}

 

Step 4: Use the jstl tag to generate an XML file

Therefore, the jstl label must be used to import two jar packages, jstl. jar and standard. jar, to the project.

Use the jstl tag to generate XML on the jsp page:

News. jsp page:

 

<%@ 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"?><newslist><c:forEach items="${newes}" var="news"><news id="${news.id}"><title>${news.title}</title><publishDate>${news.publishDate}</publishDate></news></c:forEach></newslist>

So far, the server project has been completed. Create an Android project.

2. Create an Android client:

Android project structure:


Step 1: Create the JavaBean required by the business

Tip: because both the server side and Android side projects are implemented in Java, some components can be shared, and JavaBean is one of them. At this time, we can use the JavaBean in the server project when building an Android project.

Step 2: Create the business logic layer of the Android Project

Core code: GetXmlAndParse. java:

 

Package com. jph. gxfi. service; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import java. util. arrayList; import java. util. date; import java. util. list; import org. xmlpull. v1.XmlPullParser; import com. jph. gxfi. model. news; import android. OS. handler; import android. OS. message; import android. util. xml;/*** get the xml on the network and parse * @ author jph * Date: 2014.09.26 */public class GetXmlAndP Arse {private String url = "http: // 10.219.61.117: 8080/ServerForXML/ServletForXML"; public static final int PARSESUCCWSS = 0x2001; private Handler handler; public GetXmlAndParse (Handler handler) {// TODO Auto-generated constructor stubthis. handler = handler;}/*** get XML on the Network */public void getXml () {new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {HttpURLConnection Conn = (HttpURLConnection) new URL (url ). openConnection (); conn. setConnectTimeout (5000); // set connection timeout conn. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {InputStream inputStream = conn. getInputStream (); List <News> listNews = pullXml (inputStream); if (listNews. size ()> 0) {// If the parsing result is not empty, the parsed data is sent to the UI thread Message msg = new Message (); msg. obj = listNews; msg. what = PARSESUCCWSS; handler. sendMessage (msg) ;}} catch (effectio N e) {// TODO Auto-generated catch blocke. printStackTrace () ;}// establish a connection with the server }}). start ();}/*** Parse Xml and encapsulate it into * @ param inputStream */protected List <News> pullXml (InputStream inputStream) {List <News> listNews = new ArrayList <News> (); try {XmlPullParser pullParser = Xml. newPullParser (); News news = null; pullParser. setInput (inputStream, "UTF-8"); int eventCode = pullParser. getEventType (); while (eventCode! = XmlPullParser. END_DOCUMENT) {String targetName = pullParser. getName (); switch (eventCode) {case XmlPullParser. START_TAG: if ("news ". equals (targetName) {// Start Node for processing news News = new news (); news. setId (new Integer (pullParser. getAttributeValue (0);} else if ("title ". equals (targetName) {news. setTitle (pullParser. nextText ();} else if ("publishDate ". equals (targetName) {news. setPublishDate (new Date (pullParser. nextText ();} break; case XmlPullParser. END_TAG: if ("news ". equals (targetName) {// The End Node for processing news listNews. add (news);} break;} eventCode = pullParser. next (); // parse the next node (Start Node, end node)} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}return listNews ;}}

Step 3: Create an Activity

 

Package com. jph. gxfi. activity; import java. text. simpleDateFormat; import java. util. arrayList; import java. util. date; import java. util. hashMap; import java. util. list; import java. util. map; import com. jph. gxfi. r; import com. jph. gxfi. model. news; import com. jph. gxfi. service. getXmlAndParse; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. listView; import android. widget. simpleAdapter; import android. app. activity;/*** get xml on the Network * @ author jph * Date: 2014.09.26 */public class MainActivity extends Activity {private List <News> listNews; private ListView list; handler mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubswitch (msg. what) {case GetXmlAndParse. PARSESUCCWSS: listNews = (List <News>) msg. obj; initData (); break;} super. handleMessage (msg) ;}}; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); list = (ListView) findViewById (R. id. list); GetXmlAndParse getXmlAndParse = new GetXmlAndParse (mHandler); getXmlAndParse. getXml ();}/*** fill the parsed xml into ListView */protected void initData () {// TODO Auto-generated method stubList <Map <String, object> items = new ArrayList <Map <String, Object> (); for (News news: listNews) {Map <String, Object> item = new HashMap <String, object> (); item. put ("id", news. getId (); item. put ("title", news. getTitle (); item. put ("time", convertDate (news. getPublishDate (); items. add (item);} SimpleAdapter adapter = new SimpleAdapter (this, items, R. layout. line, new String [] {"id", "title", "time"}, new int [] {R. id. tvId, R. id. tvTitle, R. id. tvTime}); list. setAdapter (adapter);} private String convertDate (Date publishDate) {// TODO Auto-generated method stubSimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH-mm-ss"); return sdf. format (publishDate );}}

 

So far, the Android project has been completed. Let's take a look at the APP running effect:

Android running:


 


In android, how does the client Use pull to read xml files on the remote server? Code

Download Method, hope to help you.

Ublic static boolean downServerVersion () throws Exception {
ApkUrl = readApkUrl ();
URL url = new URL (apkUrl );
HttpURLConnection conn = (HttpURLConnection) url
. OpenConnection ();
Conn. connect ();
Int length = conn. getContentLength ();
InputStream is = conn. getInputStream ();
File file = new File (savePath );
If (! File. exists ()){
File. mkdir ();
}
String apkFile = saveFileName;
File ApkFile = new File (apkFile );
FileOutputStream fos = new FileOutputStream (ApkFile );
Int count = 0;
Byte buf [] = new byte [1024];
Int numread = is. read (buf );
Count + = numread;
Fos. write (buf, 0, numread );
Fos. close ();
Is. close ();
Return false;
}

---------------------------------------------
---------------------------------------------
Android low-level writers can answer your questions.

Android Network Programming

Write the code yourself.
1. The server interface traverses the folder, obtains the file name list, and assembles it into xml or simple strings, such as "a.mp3, B .jsp,c.wav"
2. the Android program calls the server interface. After reading the String, use a comma to split and encapsulate the factory String [] array. In andriod, the interface is called Based on the server implementation. For example, if the server interface is a common http request, URLConnection or HttpCilent is used. Others are the same.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.