博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android访问网络系列之--服务端返回XML或JSON格式数据,Android 进行解析并显示
阅读量:5309 次
发布时间:2019-06-14

本文共 10330 字,大约阅读时间需要 34 分钟。

例子说明:用户通过访问web资源的最新电影资讯,服务器端生成XML或JSON格式数据,返回Android客户端进行显示。

此案例开发需要两个方面 WEB开发和android开发.

一.web开发相对比较简单,只是模拟一下

相关代码如下:

1.实体Bean

package ygc.yxb.domain;/** * 电影资讯实体Bean * @author YXB * */public class News {    private Integer id;              //id    private String title;        //电影名称    private Integer timelenght; //时长            public News() {            }            public News(Integer id, String title, Integer timelenght) {        this.id = id;        this.title = title;        this.timelenght = timelenght;    }    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 getTimelenght() {        return timelenght;    }    public void setTimelenght(Integer timelenght) {        this.timelenght = timelenght;    }        }

2.业务逻辑

package ygc.yxb.service.impl;import java.util.ArrayList;import java.util.List;import ygc.yxb.domain.News;import ygc.yxb.service.VideoNewsService;public class VideoNewsServiceImpl implements VideoNewsService {            /**     * 获取电影资讯的业务方法     */    public List
getLastNews(){ List
newses = new ArrayList
(); newses.add(new News(32, "大话西游", 90)); newses.add(new News(12, "轩辕剑", 40)); newses.add(new News(56, "爱情公寓", 30)); return newses; }}

3.Servlet

package ygc.yxb.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 ygc.yxb.domain.News;import ygc.yxb.service.VideoNewsService;import ygc.yxb.service.impl.VideoNewsServiceImpl;/** * 用最原始的web开发servlet请求服务器,并返回客户端数据 */public class ListServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    private VideoNewsService service = 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
videos = service.getLastNews(); String format=request.getParameter("format"); //如果用户请求的是这个路径,则返回JSON格式的数据.http://192.168.1.113:8080/videonews/ListServlet?format=json if("json".equals(format)){ //[{id:56,title:"xxxx",timelength:90}] //组拼一个JSON格式的对象 StringBuilder builder = new StringBuilder(); builder.append('['); for (News news : videos) { builder.append('{'); builder.append("id:").append(news.getId()).append(','); builder.append("title:\"").append(news.getTitle()).append("\","); builder.append("timelength:").append(news.getTimelenght()); builder.append("},"); } builder.deleteCharAt(builder.length()-1); builder.append(']'); request.setAttribute("json", builder.toString()); request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response); //如果用户请求的是这个路径,则返回XML格式的数据.http://192.168.1.113:8080/videonews/ListServlet }else{ request.setAttribute("videos", videos); request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response); } }}

4.jsp页面

4.1.jsonvideonews.jsp

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

4.2.videonews.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" %>
${video.title }
${video.timelenght}

到此为止web开发完毕,现在Android开发相关代码

1.实体Bean

package ygc.yxb.domain;public class News {    private Integer id;    private String title;    private Integer timelenght;            public News() {            }            public News(Integer id, String title, Integer timelenght) {        this.id = id;        this.title = title;        this.timelenght = timelenght;    }    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 getTimelenght() {        return timelenght;    }    public void setTimelenght(Integer timelenght) {        this.timelenght = timelenght;    }        }

2.业务逻辑

package ygc.yxb.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 ygc.yxb.domain.News;import ygc.yxb.utils.StreamTool;public class VideoNewsService {        /**     * 获取最新的视频资讯接受服务器端XML格式的数据     * @return     * @throws Exception     */    public static List
getLastNews() throws Exception{ String path="http://192.168.1.113:8080/videonews/ListServlet"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); return parseXML(inStream); } return null; } /** * 获取最新的视频资讯 接受服务器端JSON格式的数据 * @return * @throws Exception */ public static List
getJSONLastNews() throws Exception{ String path="http://192.168.1.113:8080/videonews/ListServlet?format=json"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); return parseJSON(inStream); } return null; } /** * 解析JSON数据 * @param inStream * @return */ private static List
parseJSON(InputStream inStream) throws Exception { List
newses = new ArrayList
(); byte[] data =StreamTool.read(inStream); //将字节数组转换成字符串 String json= new String(data); //将json对象转换成json的数组对象 JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject=array.getJSONObject(i); News news=new News(jsonObject.getInt("id"),jsonObject.getString("title"),jsonObject.getInt("timelength")); newses.add(news); } return newses; } /** * 解析服务器返回的XML数据 * @param inStream * @return */ private static List
parseXML(InputStream inStream) throws Exception{ List
newses = new ArrayList
(); News news = null; //用Pull解析器解析XML文件 XmlPullParser parser= Xml.newPullParser(); parser.setInput(inStream, "UTF-8"); //得到开始文档XML事件 int event = parser.getEventType(); //不等于结束事件,循环读取XML文件并封装成对象 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.setTimelenght(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; } }

3.Activity

package ygc.yxb.news;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import ygc.yxb.domain.News;import ygc.yxb.service.VideoNewsService;import android.app.Activity;import android.os.Bundle;import android.widget.ListView;import android.widget.SimpleAdapter;public class MainActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                ListView listView=(ListView)this.findViewById(R.id.listView);                try {            List
videos=VideoNewsService.getJSONLastNews(); List
> data = new ArrayList
>(); for (News news : videos) { HashMap
item = new HashMap
(); item.put("id", news.getId()); item.put("title", news.getTitle()); item.put("timelength", getResources().getString(R.string.timelength)+ news.getTimelenght()+getResources().getString(R.string.min)); data.add(item); } //用SimpleAdapter 绑定ListView控件 SimpleAdapter adapter = new SimpleAdapter(this,data, R.layout.item,new String[]{"title","timelength"}, new int[]{R.id.title,R.id.timelength}); listView.setAdapter(adapter); } catch (Exception e) { e.printStackTrace(); } }}

4读取数据流工具类:

package ygc.yxb.utils;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool {    /**     * 读取流中的数据     * @param inStream     * @return     * @throws Exception     */    public static byte[] read(InputStream inStream) throws Exception {        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();        byte[] buffer = new byte[1024];        int len = 0;        //如果字节流中的数据不等于-1,就说明一直有,然后循环读出        while( (len=inStream.read(buffer)) !=-1){            //将读出的数据放入内存中            outputStream.write(buffer);                    }        inStream.close();        return outputStream.toByteArray();    }}

这里android 开发完毕,而显示的控件是ListView 最后在清单文件中,配置访问网络的权限即可。

运行效果如下:

 

转载于:https://www.cnblogs.com/xiaobing-yang/archive/2012/08/09/2629530.html

你可能感兴趣的文章
Competing Consumers Pattern (竞争消费者模式)
查看>>
Android面试收集录15 Android Bitmap压缩策略
查看>>
PHP魔术方法之__call与__callStatic方法
查看>>
ubuntu 安装后的配置
查看>>
web前端之路,js的一些好书(摘自聂微东 )
查看>>
【模板】对拍程序
查看>>
【转】redo与undo
查看>>
解决升级系统导致的 curl: (48) An unknown option was passed in to libcurl
查看>>
Java Session 介绍;
查看>>
spoj TBATTLE 质因数分解+二分
查看>>
Django 模型层
查看>>
dedecms讲解-arc.listview.class.php分析,列表页展示
查看>>
Extjs6 经典版 combo下拉框数据的使用及动态传参
查看>>
【NodeJS】http-server.cmd
查看>>
研磨JavaScript系列(五):奇妙的对象
查看>>
面试题2
查看>>
selenium+java iframe定位
查看>>
P2P综述
查看>>
第五章 如何使用Burp Target
查看>>
Sprint阶段测试评分总结
查看>>