Android开发18——获取网络资源之json数据

一、项目背景
在Android开发中有一项非常广泛的应用:Android项目获取另一个web项目的资源或者返回的数据。

本文获取web项目返回的JSON数据。Android应用解析JSON比XML性能要好,但有许多项目仍然采用的是XML。

 

 

二、实例代码

Web项目

/**
 * 新闻业务类
 * 
 * @author 徐越
 * 
 */
public class VideoNewsServiceImpl implements VideoNewsService
{
	public List<VideoNews> readNews()
	{
		List<VideoNews> lst = new ArrayList<VideoNews>();
		lst.add(new VideoNews(1, "喜洋洋", 20));
		lst.add(new VideoNews(2, "变形金刚", 10));
		lst.add(new VideoNews(3, "功夫熊猫", 20));
		return lst;
	}
}

/**
 * 新闻Servlet
 * 
 * @author 徐越
 * 
 */
public class ListServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private VideoNewsService vs = new VideoNewsServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		List<VideoNews> news = vs.readNews();
		JSONArray jsonarr = JSONArray.fromObject(news);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.getWriter().print(jsonarr);
	}
}


Android项目

public class VideoNewsServiceImpl implements VideoNewsService
{

	/**
	 * 获取最新视频资讯,从JSON文件中,解析效率高
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<VideoNews> getNewsFromJson() throws Exception
	{
		List<VideoNews> lst = new ArrayList<VideoNews>();
		String path = "http://xxx.xxx.xxx.xxx:8080/web/ListServlet";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(5000);
		conn.setRequestMethod("GET");
		if (200 == conn.getResponseCode())
		{
			InputStream instream = conn.getInputStream();
			lst = parseJSON(instream);
		}
		return lst;
	}

	/**
	 * 解析JSON
	 */
	private List<VideoNews> parseJSON(InputStream instream) throws Exception
	{
		List<VideoNews> lst = new ArrayList<VideoNews>();
		byte[] data = IOUtils.read(instream);
		String jsonStr = new String(data);
		JSONArray array = new JSONArray(jsonStr);
		for (int i = 0; i < array.length(); i++)
		{
			JSONObject jsonObj = (JSONObject) array.getJSONObject(i);
			VideoNews v = new VideoNews(jsonObj.getInt("id"), 
					jsonObj.getString("title"), jsonObj.getInt("timeLength"));
			lst.add(v);
		}
		return lst;
	}
}

/**
 * IO操作工具类
 * 
 * @author 徐越
 * 
 */
public class IOUtils
{
	/**
	 * 读取输入流为byte[]数组
	 */
	public static byte[] read(InputStream instream) throws IOException
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = instream.read(buffer)) != -1)
		{
			bos.write(buffer, 0, len);
		}
		return bos.toByteArray();
	}
}

需要指出的是

在web项目中我采用的是net.sf.json下的类对JSON进行解析,而Android项目中默认自带的JSON包是org.json。API有所不同,只要熟悉一下即可。

 

上一篇:InnoDB事务结构体代码变量列表


下一篇:Android开发14——监听内容提供者ContentProvider的数据变化