1.模拟服务器
a.新建一个JAVAWEB项目,也就是这里要充当的服务器,模拟一个业务,并且返回一个XML类型的数据,当然后JSON也行,但是这里我先使用XML,JSON格式的 后续进行实现。下面图片是通过访问服务器返回的XML数据
b.新建一个android项目,访问服务器,并解析服务器返回的数据
1.新建一个实体类
2.访问服务器地址,解析数据/** * 实体bean,用来将解析后的数据封装为对象 */ public class News { private Integer id; private String title; private Integer timelength; public News(){ } public News(Integer id, String title, Integer timelength) { this.id = id; this.title = title; this.timelength = timelength; } 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 getTimelength() { return timelength; } public void setTimelength(Integer timelength) { this.timelength = timelength; } }
3.将数据显示在ListView中,至于ListView显示数据这里不在进行介绍,请访问我之前发表的博文 ListView绑定数据import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; import cn.kafei.bean.News; public class NewsService { /** * 获取最新视频资讯 */ public static List<News> getListNews() throws Exception { // 服务器地址URL,在操作系统上测试访问项目时使用localhost(127.0.0.1)进行访问,但在这里需要将localhost(127.0.0.1)替换为 // 本机在局域网或者外网中的IP地址。因为android和WEB项目运行在不同的平台上 String path = "http://192.168.1.109:8080/ListServlet"; URL url = new URL(path);// 构建一个URL对象 HttpURLConnection con = (HttpURLConnection) url.openConnection();// 打开连接 con.setConnectTimeout(5000);// 设置超时时间 con.setRequestMethod("GET");// 设置请求方式 if (con.getResponseCode() == 200) {// 判断是否请求成功,状态码为200 InputStream inStream = con.getInputStream(); return parseXML(inStream); } return null; } /** * 解析服务器返回的XML数据 * * @param inStream */ private static List<News> parseXML(InputStream inStream) throws Exception { List<News> newList = new ArrayList<News>(); News news = null; XmlPullParser parser = Xml.newPullParser(); parser.setInput(inStream, "UTF-8"); int event = parser.getEventType(); 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.setTimelength(new Integer(parser.nextText())); } break; case XmlPullParser.END_TAG: if ("news".equals(parser.getName())) { newList.add(news); news = null; } break; } event = parser.next(); } return newList; } }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import cn.kafei.bean.News; import cn.kafei.service.NewsService; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; public class NewsActivity extends Activity { private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView) this.findViewById(R.id.listView);// listView显示控件 try { List<News> news = NewsService.getListNews();// 获取服务器请求返回的数据信息 List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (News n : news) { HashMap<String, Object> item = new HashMap<String, Object>(); item.put("id", n.getId()); item.put("title", n.getTitle()); item.put( "timelength", getResources().getString(R.string.timeLength) + n.getTimelength() + getResources().getString(R.string.min)); data.add(item); } SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[] { "title", "timelength" }, new int[] { R.id.title, R.id.timelength }); listView.setAdapter(adapter);// 将SimpleAdapter适配器将数据绑定在ListView上 } catch (Exception e) { e.printStackTrace(); } } }
4.解析JSON的方法
服务端组件JSON字符串:/** * 获取服务器端JSON格式数据 */ public static List<News> getListNewsJson() throws Exception { // 服务器地址URL,在操作系统上测试访问项目时使用localhost(127.0.0.1)进行访问,但在这里需要将localhost(127.0.0.1)替换为 // 本机在局域网或者外网中的IP地址。因为android和WEB项目运行在不同的平台上 String path = "http://192.168.1.109:8080/ListServlet?format=json"; URL url = new URL(path);// 构建一个URL对象 HttpURLConnection con = (HttpURLConnection) url.openConnection();// 打开连接 con.setConnectTimeout(5000);// 设置超时时间 con.setRequestMethod("GET");// 设置请求方式 if (con.getResponseCode() == 200) {// 判断是否请求成功,状态码为200 InputStream inStream = con.getInputStream(); return parseJSON(inStream); } return null; } /** * 解析JSON数据 * @param inStream * @return * @throws IOException */ private static List<News> parseJSON(InputStream inStream) throws Exception { List<News> newsList=new ArrayList<News>(); byte[] data=read(inStream); String json=new String(data); 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")); newsList.add(news); } return newsList; } /** * 读取流中的数据 */ public static byte[] read(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); byte[] b=new byte[1024]; int len=0; while((len=inputStream.read(b))!=-1){ outputStream.write(b); } inputStream.close(); return outputStream.toByteArray(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<News> news=service.getListNews(); String format=request.getParameter("format"); if("json".equals(format)){ StringBuilder builder=new StringBuilder(); builder.append('['); for(News n:news){ builder.append('{'); builder.append("id:").append(n.getId()).append(','); builder.append("title:\"").append(n.getTitle()).append("\","); builder.append("timelength:").append(n.getTimelength()); builder.append("},"); } builder.deleteCharAt(builder.length()-1); builder.append(']'); //将新闻放到request对象中 request.setAttribute("json", builder.toString()); request.getRequestDispatcher("/WEB-INF/page/newsjson.jsp").forward(request, response); }else{ //将新闻放到request对象中 request.setAttribute("news", news); //用转发将数据显示的页面上 request.getRequestDispatcher("/WEB-INF/page/news.jsp").forward(request, response); } }
5.显示效果
源码下载地址:android访问网络源码