我的Android进阶之旅------>Android获取服务器上格式为JSON和XML两种格式的信息的小程序

来源:互联网 发布:java运算类型 编辑:程序博客网 时间:2024/05/25 05:38

 

首先写一个应用服务器端的jsp程序,用jsp和servlet简单实现,如下图所示

 

 

[java] view plain copy
  1. package cn.roco.domain;  
  2.   
  3. public class News {  
  4.     private Integer id;  
  5.     private String title;  
  6.     private Integer timelength;  
  7.   
  8.     public News() {  
  9.     }  
  10.   
  11.     public News(Integer id, String title, Integer timelength) {  
  12.         this.id = id;  
  13.         this.title = title;  
  14.         this.timelength = timelength;  
  15.     }  
  16.   
  17.     public Integer getId() {  
  18.         return id;  
  19.     }  
  20.   
  21.     public void setId(Integer id) {  
  22.         this.id = id;  
  23.     }  
  24.   
  25.     public String getTitle() {  
  26.         return title;  
  27.     }  
  28.   
  29.     public void setTitle(String title) {  
  30.         this.title = title;  
  31.     }  
  32.   
  33.     public Integer getTimelength() {  
  34.         return timelength;  
  35.     }  
  36.   
  37.     public void setTimelength(Integer timelength) {  
  38.         this.timelength = timelength;  
  39.     }  
  40.   
  41. }  

 

 

[java] view plain copy
  1. package cn.roco.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import cn.roco.domain.News;  
  6.   
  7. public interface VideoNewsService {  
  8.   
  9.     /** 
  10.      * 获取最新视频资讯 
  11.      * @return 
  12.      */  
  13.     public List<News> getLastNews();  
  14.   
  15. }  



 

[java] view plain copy
  1. package cn.roco.service.impl;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import cn.roco.domain.News;  
  7. import cn.roco.service.VideoNewsService;  
  8.   
  9. public class VideoNewsServiceBean implements VideoNewsService{  
  10.     /** 
  11.      * 模拟从服务器中获取数据  返回 
  12.      */  
  13.     public List<News> getLastNews(){  
  14.         List<News> newses=new ArrayList<News>();  
  15.         for (int i = 1; i < 30; i++) {  
  16.             newses.add(new News(i,"Xili"+i,i+90));  
  17.         }  
  18.         return newses;  
  19.     }  
  20. }  


 
 

[java] view plain copy
  1. package cn.roco.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import cn.roco.domain.News;  
  12. import cn.roco.service.VideoNewsService;  
  13. import cn.roco.service.impl.VideoNewsServiceBean;  
  14.   
  15. public class ListServlet extends HttpServlet {  
  16.       
  17.     private VideoNewsService newsService=new VideoNewsServiceBean();  
  18.       
  19.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  20.             throws ServletException, IOException {  
  21.         List<News> videos=newsService.getLastNews();  
  22.         String format=req.getParameter("format");  
  23.         //返回JSON格式  
  24.         if ("json".equals(format)) {  
  25.             StringBuilder builder=new StringBuilder();  
  26.             builder.append('[');  
  27.             for (News news : videos) {  
  28.                 builder.append('{');  
  29.                 builder.append("id:").append(news.getId()).append(',');  
  30.                 //转义 ""双引号  
  31.                 builder.append("title:\"").append(news.getTitle()).append("\",");  
  32.                 builder.append("timelength:").append(news.getTimelength());  
  33.                 builder.append("},");  
  34.             }  
  35.             builder.deleteCharAt(builder.length()-1);//去掉最后的','  
  36.             builder.append(']');  
  37.             req.setAttribute("json", builder.toString());  
  38.             req.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(req, resp);  
  39.         }else{  
  40.             //返回XML格式  
  41.             req.setAttribute("videos", videos);  
  42.             req.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(req, resp);  
  43.         }  
  44.     }  
  45.   
  46.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  47.             throws ServletException, IOException {  
  48.         doGet(req, resp);  
  49.     }  
  50. }  


 

 如果要返回XML文件  就forward到videonews.jsp页面

[html] view plain copy
  1. <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><?xml version="1.0" encoding="UTF-8"?>  
  2. <videonews>   
  3.     <c:forEach items="${videos}" var="video">  
  4.         <news id="${video.id}">  
  5.             <title>${video.title}</title>  
  6.             <timelength>${video.timelength}</timelength>   
  7.         </news>  
  8.     </c:forEach>   
  9. </videonews>  


如果要返回XML文件  就forward到videonews.jsp页面 如果要返回JSON文件 就forward到jsonvideonews.jsp页面

[html] view plain copy
  1. <%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. ${json}  

 

web.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <servlet>  
  8.     <description>This is the description of my J2EE component</description>  
  9.     <display-name>This is the display name of my J2EE component</display-name>  
  10.     <servlet-name>ListServlet</servlet-name>  
  11.     <servlet-class>cn.roco.servlet.ListServlet</servlet-class>  
  12.   </servlet>  
  13.   
  14.   <servlet-mapping>  
  15.     <servlet-name>ListServlet</servlet-name>  
  16.     <url-pattern>/ListServlet</url-pattern>  
  17.   </servlet-mapping>  
  18.   <welcome-file-list>  
  19.     <welcome-file>index.jsp</welcome-file>  
  20.   </welcome-file-list>  
  21. </web-app>  


 


 

服务器端写好之后,就开始写Android应用

架构如下图所示:

 

[java] view plain copy
  1. package cn.roco.news.domain;  
  2. public class News {  
  3.     private Integer id;  
  4.     private String title;  
  5.     private Integer timelength;  
  6.   
  7.     public News() {  
  8.     }  
  9.   
  10.     public News(Integer id, String title, Integer timelength) {  
  11.         this.id = id;  
  12.         this.title = title;  
  13.         this.timelength = timelength;  
  14.     }  
  15.   
  16.     public Integer getId() {  
  17.         return id;  
  18.     }  
  19.   
  20.     public void setId(Integer id) {  
  21.         this.id = id;  
  22.     }  
  23.   
  24.     public String getTitle() {  
  25.         return title;  
  26.     }  
  27.   
  28.     public void setTitle(String title) {  
  29.         this.title = title;  
  30.     }  
  31.   
  32.     public Integer getTimelength() {  
  33.         return timelength;  
  34.     }  
  35.   
  36.     public void setTimelength(Integer timelength) {  
  37.         this.timelength = timelength;  
  38.     }  
  39.   
  40. }  


 

[java] view plain copy
  1. package cn.roco.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.InputStream;  
  5.   
  6. public class StremTools {  
  7.     /** 
  8.      * 读取输入流中的数据 
  9.      * @param inputStream  输入流 
  10.      * @return   二进制的流数据 
  11.      * @throws Exception 
  12.      */  
  13.     public static byte[] read(InputStream inputStream) throws Exception {  
  14.         ByteArrayOutputStream outputStream=new ByteArrayOutputStream();  
  15.         byte[] buffer=new byte[1024];  
  16.         int length=0;  
  17.         while((length=inputStream.read(buffer))!=-1){  
  18.             outputStream.write(buffer,0,length);  
  19.         }  
  20.         inputStream.close();  
  21.         return outputStream.toByteArray();  
  22.     }  
  23.   
  24. }  


 

[java] view plain copy
  1. package cn.roco.news.service;  
  2.   
  3. import java.io.InputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.json.JSONArray;  
  10. import org.json.JSONObject;  
  11. import org.xmlpull.v1.XmlPullParser;  
  12.   
  13. import android.util.Xml;  
  14.   
  15. import cn.roco.news.domain.News;  
  16. import cn.roco.utils.StremTools;  
  17.   
  18. public class VideoNewsService {  
  19.       
  20.     /** 
  21.      * 获取最新的视频资讯 
  22.      * 采用JSON格式 
  23.      * @param path 
  24.      * @return 
  25.      * @throws Exception 
  26.      */  
  27.     public static List<News> getJSONLastNews(String path) throws Exception {  
  28.         URL url = new URL(path);  
  29.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 基于HTTP协议连接对象  
  30.         connection.setConnectTimeout(5000);  
  31.         connection.setRequestMethod("GET");  
  32.         if (connection.getResponseCode() == 200) {  
  33.             InputStream inputStream = connection.getInputStream();  
  34.             return parseJSON(inputStream);  
  35.         }else{  
  36.             throw new RuntimeException("服务器响应失败");  
  37.         }  
  38.     }  
  39.     /** 
  40.      * 解析服务器返回的JSON数据 
  41.      *  
  42.      * @param inputStream 
  43.      * @return 
  44.      * @throws Exception  
  45.      */  
  46.     private static List<News> parseJSON(InputStream inputStream) throws Exception {  
  47.         List<News> newses=new ArrayList<News>();  
  48.         byte[] data=StremTools.read(inputStream);  
  49.         String jsonData=new String(data,"UTF-8");  
  50.         JSONArray array=new JSONArray(jsonData);   
  51.         for (int i = 0; i < array.length(); i++) {  
  52.              JSONObject jsonObject= array.getJSONObject(i);  
  53.              News news=new News( jsonObject.getInt("id"), jsonObject.getString("title"),jsonObject.getInt("timelength"));  
  54.              newses.add(news);  
  55.         }  
  56.         return newses;  
  57.     }  
  58.   
  59.     /** 
  60.      * 获取最新的视频资讯 
  61.      * 采用XML格式 
  62.      * @param path 
  63.      * @return 
  64.      * @throws Exception 
  65.      */  
  66.     public static List<News> getLastNews(String path) throws Exception {  
  67.         URL url = new URL(path);  
  68.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 基于HTTP协议连接对象  
  69.         connection.setConnectTimeout(5000);  
  70.         connection.setRequestMethod("GET");  
  71.         if (connection.getResponseCode() == 200) {  
  72.             InputStream inputStream = connection.getInputStream();  
  73.             return parseXML(inputStream);  
  74.         }  
  75.         return null;  
  76.     }  
  77.   
  78.     /** 
  79.      * 解析服务器返回的XML数据 
  80.      *  
  81.      * @param inputStream 
  82.      * @return 
  83.      */  
  84.     private static List<News> parseXML(InputStream inputStream) throws Exception {  
  85.         List<News> newses = new ArrayList<News>();  
  86.         News news = null;  
  87.         XmlPullParser parser = Xml.newPullParser();  
  88.         parser.setInput(inputStream, "UTF-8");  
  89.         int event = parser.getEventType();  
  90.         while (event != XmlPullParser.END_DOCUMENT) {  
  91.             switch (event) {  
  92.             case XmlPullParser.START_TAG:  
  93.                 if ("news".equals(parser.getName())) {  
  94.                     int id = new Integer(parser.getAttributeValue(0));  
  95.                     news = new News();  
  96.                     news.setId(id);  
  97.                 } else if ("title".equals(parser.getName())) {  
  98.                     news.setTitle(parser.nextText());  
  99.                 } else if ("timelength".equals(parser.getName())) {  
  100.                     news.setTimelength(new Integer(parser.nextText()));  
  101.                 }  
  102.                 break;  
  103.             case XmlPullParser.END_TAG:  
  104.                 if ("news".equals(parser.getName())) {  
  105.                     newses.add(news);  
  106.                     news = null;  
  107.                 }  
  108.                 break;  
  109.             }  
  110.             event = parser.next();  
  111.         }  
  112.         return newses;  
  113.     }  
  114. }  

[java] view plain copy
  1. package cn.roco.news;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6.   
  7. import cn.roco.news.domain.News;  
  8. import cn.roco.news.service.VideoNewsService;  
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.widget.ListView;  
  12. import android.widget.SimpleAdapter;  
  13. import android.widget.Toast;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.   
  22.         ListView listView = (ListView) findViewById(R.id.listView);  
  23.         try {  
  24.             //采用XML格式  
  25. //          String xmlPath="http://192.168.15.58:8080/Hello/ListServlet";  
  26. //          List<News> videos = VideoNewsService.getLastNews();  
  27.               
  28.             //采用JSON格式  
  29.             String jsonPath="http://192.168.15.58:8080/Hello/ListServlet?format=json";  
  30.             List<News> videos = VideoNewsService.getJSONLastNews(jsonPath);  
  31.           
  32.             List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  
  33.             for (News news : videos) {  
  34.                 HashMap<String, Object> item = new HashMap<String, Object>();  
  35.                 item.put("id", news.getId());  
  36.                 item.put("title", news.getTitle());  
  37.                 item.put(  
  38.                         "timelength",  
  39.                         getResources().getString(R.string.timelength)  
  40.                                 + news.getTimelength()  
  41.                                 + getResources().getString(R.string.min));  
  42.                 data.add(item);  
  43.             }  
  44.             SimpleAdapter adapter = new SimpleAdapter(this, data,  
  45.                     R.layout.item, new String[] { "title""timelength" },  
  46.                     new int[] { R.id.title, R.id.timelength });  
  47.             listView.setAdapter(adapter);  
  48.         } catch (Exception e) {  
  49.             Toast.makeText(getApplicationContext(), "有错"1);  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53. }  


 item.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="horizontal" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <TextView android:id="@+id/title" android:layout_width="200dp"  
  6.         android:layout_height="wrap_content"/>  
  7.     <TextView android:id="@+id/timelength" android:layout_width="fill_parent"  
  8.         android:layout_height="wrap_content"/>  
  9. </LinearLayout>  


main.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.   
  6.     <LinearLayout android:orientation="horizontal"  
  7.         android:layout_width="wrap_content" android:layout_height="wrap_content">  
  8.         <TextView android:text="@string/title" android:layout_width="200dp"  
  9.             android:layout_height="wrap_content" />  
  10.         <TextView android:text="@string/details" android:layout_width="wrap_content"  
  11.             android:layout_height="wrap_content" />  
  12.     </LinearLayout>  
  13.   
  14.     <ListView android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content" android:id="@+id/listView" />  
  16. </LinearLayout>  

 

string.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, MainActivity!</string>  
  4.     <string name="app_name">视频资讯</string>  
  5.     <string name="timelength">时长:</string>  
  6.     <string name="min">分钟</string>  
  7.     <string name="title">标题</string>  
  8.     <string name="details">详情</string>  
  9. </resources>  

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="cn.roco.news"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.    <!-- 访问Internet权限 -->  
  8.     <uses-permission android:name="android.permission.INTERNET"/>  
  9.   
  10.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  11.         <activity android:name=".MainActivity"  
  12.                   android:label="@string/app_name">  
  13.             <intent-filter>  
  14.                 <action android:name="android.intent.action.MAIN" />  
  15.                 <category android:name="android.intent.category.LAUNCHER" />  
  16.             </intent-filter>  
  17.         </activity>  
  18.   
  19.     </application>  
  20. </manifest>  

 

运行效果如图所示:
 

0 0
原创粉丝点击