请尊重他人的劳动成果,转载请注明出处:Android网络编程之获取网络上的XML
为要获取网络上的XML所以需要服务器端提供的支持。
一、创建服务器端:
服务器端项目结构:
服务器端运行效果图:
第一步:创建业务所需的JavaBean
package com.jph.server.model;
import java.util.Date;
/**
* 新闻实体类
* @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;
}
}
第二步:创建业务逻辑接口和具体实现类
业务接口:
package com.jph.server.service;
import java.util.List;
import com.jph.server.model.News;
public interface XMLService {
/**
* 获取最新的资讯
* @return
*/
public List<News> getLastNews();
}
业务接口的实现类:
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 {
/**
* 获取最新的视频资讯
* @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;
}
}
第三步:创建控制器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;
/**
* 负责响应客户端的请求: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, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<News> newes = newsService.getLastNews();//获取最新的视频资讯
request.setAttribute("newes", newes);
//将客户端的请求转向news.jsp页面
request.getRequestDispatcher("/WEB-INF/page/news.jsp").forward(request, response);
}
}
第四步:使用jstl标签生成XML文件
因此需要使用jstl标签所以需要将jstl.jar与standard.jar两个jar包导入项目中。
使用jstl标签在jsp页面生成XML:
news.jsp页面:
<%@ 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>
至此服务器端项目已经完成。下面开始创建Android端项目。
二、创建Android端:
Android端项目结构:
第一步:创建业务所需的JavaBean
提示:因为服务器端和Android端项目都是用Java语言实现的,所以一些组件可以共用,JavaBean便是其中之一。此时我们在搭建Android端项目的时候,完全可以将服务器端项目中JavaBean拿来用。
第二步:创建Android端项目的业务逻辑层
核心代码: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;
/**
* 获取网络上的xml,并解析
* @author jph
* Date:2014.09.26
*/
public class GetXmlAndParse {
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 stub
this.handler=handler;
}
/**
* 获取网络上的XML
*/
public void getXml(){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpURLConnection conn=(HttpURLConnection)new
URL(url).openConnection();
conn.setConnectTimeout(5000);//设置连接超时
conn.setRequestMethod("GET");
if (conn.getResponseCode()==200) {
InputStream inputStream=conn.getInputStream();
List<News> listNews=pullXml(inputStream);
if (listNews.size()>0) {//如果解析结果不为空则将解析出的数据发送给UI线程
Message msg=new Message();
msg.obj=listNews;
msg.what=PARSESUCCWSS;
handler.sendMessage(msg);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//和服务器建立连接
}
}).start();
}
/**
* 解析Xml,并将其封装成
* @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)) {//处理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)) {//处理news的结束节点
listNews.add(news);
}
break;
}
eventCode=pullParser.next();//解析下一个节点(开始节点,结束节点)
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listNews;
}
}
第三步:创建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;
/**
* 获取网络上的xml
* @author jph
* Date:2014.09.26
*/
public class MainActivity extends Activity {
private List<News>listNews;
private ListView list;
Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case GetXmlAndParse.PARSESUCCWSS:
listNews=(List<News>) msg.obj;
initData();
break;
}
super.handleMessage(msg);
}
};
@Override
protected 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();
}
/**
* 将解析后的xml填充到ListView
*/
protected void initData() {
// TODO Auto-generated method stub
List<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 stub
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
return sdf.format(publishDate);
}
}
至此Android端项目已经完成了。下面就让我们看一下APP运行效果吧:
Android运行效果图: