android从web应用读取xml和json数据实战

一、web应用主要代码:

1、domian News.java

package com.caiz.news.domain;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 新闻实体类
* @author HuangYucai
*/
public class News {
private Long id;
private String title;
private Date createTime;
public static final SimpleDateFormat SDF=new SimpleDateFormat("yyyy-MM-dd");
public News() {
}
public News(Long id, String title, Date createTime) {
this.id = id;
this.title = title;
this.createTime = createTime;
}

public News(long id, String title, String dateStr) throws Exception {

this.id=id;
this.title=title;
this.createTime=SDF.parse(dateStr);
}

public String getCreateTimeStr(){
return SDF.format(this.createTime);
}
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}

 

2、service
接口Interface:INewsService

package com.caiz.web.service;

import java.util.List;

import com.caiz.web.domain.News;

public interface INewsService {

public abstract List<News> getNewsList();

}

实现类implementation:NewsServiceImpl

package com.caiz.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.caiz.web.domain.News;
import com.caiz.web.service.INewsService;

/**
* 新闻的service类
* @author HuangYucai
*
*/
public class NewsServiceImpl implements INewsService {
@Override
public List<News> getNewsList(){
List<News> newsList=new ArrayList<News>();
Date dt=new Date();
newsList.add(new News(1L,"国家兴亡,匹夫有责",dt));
newsList.add(new News(2L,"静水流深,谦者有为",dt));
newsList.add(new News(3L,"自助者,天助之",dt));
return newsList;
}
}

 

3、servlet
package com.caiz.web.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caiz.web.domain.News;
import com.caiz.web.service.INewsService;
import com.caiz.web.service.impl.NewsServiceImpl;

/**
*servlet类
*@author HuangYucai
*
*/

@WebServlet("/NewsServeLet")
public class NewsServelet extends HttpServlet {
private static final long serialVersionUID = 1L;

private INewsService newsService;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
newsService = new NewsServiceImpl();
List<News> newsList = newsService.getNewsList();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
if ("json".equals(request.getParameter("dataFormat"))) {
StringBuilder bulder=new StringBuilder("[");
for(int i=0;i<newsList.size();i++){
News news=newsList.get(i);
bulder.append("{");
bulder.append("id:").append(news.getId()).append(",");
bulder.append("title:\"").append(news.getTitle()).append("\",");
bulder.append("createDate:\"").append(sdf.format(news.getCreateTime())).append("\"");
bulder.append("},");
}
bulder=bulder.deleteCharAt(bulder.length()-1);
bulder.append("]");
request.setAttribute("jsonData", bulder.toString());
request.getRequestDispatcher("news_json.jsp").forward(request,
response);
} else {
request.setAttribute("newsList", newsList);
request.getRequestDispatcher("news_xml.jsp").forward(request,
response);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

4、jsp

xml:

 

<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <?xml version="1.0" encoding="UTF-8"?>
<root>
<c:forEach items="${newsList}" var="news">
<news id="${news.id}">
<title>${news.title}</title>
<createTime>
<fmt:formatDate value="${news.createTime}" pattern="yyyy-MM-dd"/>
</createTime>
</news>
</c:forEach>
</root>

 

json:

 

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

 

 

二、Android端:

 

1、界面:

listview的item:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >


<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/title"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/createTime"
/>

</LinearLayout>

 

主界面:main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/newsView"/>
</LinearLayout>

2、主Activity

 

 

package com.caiz.news;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.caiz.news.domain.News;
import com.caiz.news.service.NewsService;

/**
* 新闻显示的Activity
* @author HuangYucai
*
*/
public class NewsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) this.findViewById(R.id.newsView);
try {
List<News> newsList = NewsService.getNewsList();
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
if (newsList != null) {//有数据则显示
Log.i("length", String.valueOf(newsList.size()));
for (News news : newsList) {
HashMap<String, Object> mps = new HashMap<String, Object>();
mps.put("id", news.getId());
mps.put("title", news.getTitle());
mps.put("createTime",news.getCreateTimeStr());
data.add(mps);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
R.layout.items, new String[] { "title", "createTime" },
new int[] { R.id.title, R.id.createTime });
listView.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

3、service类

 

package com.caiz.news.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
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 com.caiz.news.domain.News;


/**
* Service类
* @author HuangYucai
*
*/

public class NewsService {

//请求新闻的主方法
public static List<News> getNewsList() throws Exception {
String path = "http://192.168.0.186:8080/web/NewsServeLet?dataFormat=json";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream iStream = conn.getInputStream();
return ParseJSON(iStream);
}
return null;
}

//解析json数据
public static List<News> ParseJSON(InputStream iStream) throws Exception{
List<News> newsList=new ArrayList<News>();
String jsonStr=ParseString(iStream);
JSONArray jArray=new JSONArray(jsonStr);
for(int i=0;i<jArray.length();i++){
JSONObject jObject=(JSONObject) jArray.get(i);
News news=new News(jObject.getLong("id"),jObject.getString("title"),jObject.getString("createDate"));
newsList.add(news);
}
return newsList;
}

//输入流换成字符串
public static String ParseString(InputStream iStream) throws Exception {
if(iStream==null){
return "null";
}
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=iStream.read(buf))>0){
bos.write(buf,0,len);
}
return new String(bos.toByteArray(),"UTF-8");
}

//解析XML数据
public static List<News> ParseXML(InputStream iStream) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(iStream, "UTF-8");
int event = parser.getEventType();
News news = null;
ArrayList<News> newsList = new ArrayList<News>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
if ("news".equals(parser.getName())) {
Long id = new Long(parser.getAttributeValue(0));
news = new News();
news.setId(id);
}else if ("title".equals(parser.getName())) {
news.setTitle(parser.nextText());
}else if("createTime".equals(parser.getName())) {
news.setCreateTime(sdf.parse(parser.nextText()));
}
break;
case XmlPullParser.END_TAG:
if ("news".equals(parser.getName())) {
newsList.add(news);
news=null;
}
break;
}
event = parser.next();
}

return newsList;
}
}

4、domain同web端

你可能感兴趣的:(android,xml,Web,json)