Android獲取服務器上格式為JSON和XML兩種格式的信息的小程序

jopen 11年前發布 | 179K 次閱讀 Android Android開發 移動開發

首先寫一個應用服務器端的jsp程序,用jsp和servlet簡單實現,如下圖所示

Android獲取服務器上格式為JSON和XML兩種格式的信息的小程序

 

 

package cn.roco.domain;

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;
    }

}

 

 

package cn.roco.service;

import java.util.List;

import cn.roco.domain.News;

public interface VideoNewsService {

    /**
     * 獲取最新視頻資訊
     * @return
     */
    public List<News> getLastNews();

}



 

package cn.roco.service.impl;

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

import cn.roco.domain.News;
import cn.roco.service.VideoNewsService;

public class VideoNewsServiceBean implements VideoNewsService{
    /**
     * 模擬從服務器中獲取數據  返回
     */
    public List<News> getLastNews(){
        List<News> newses=new ArrayList<News>();
        for (int i = 1; i < 30; i++) {
            newses.add(new News(i,"Xili"+i,i+90));
        }
        return newses;
    }
}


 
 

package cn.roco.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 cn.roco.domain.News;
import cn.roco.service.VideoNewsService;
import cn.roco.service.impl.VideoNewsServiceBean;

public class ListServlet extends HttpServlet {

    private VideoNewsService newsService=new VideoNewsServiceBean();

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        List<News> videos=newsService.getLastNews();
        String format=req.getParameter("format");
        //返回JSON格式
        if ("json".equals(format)) {
            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.getTimelength());
                builder.append("},");
            }
            builder.deleteCharAt(builder.length()-1);//去掉最后的','
            builder.append(']');
            req.setAttribute("json", builder.toString());
            req.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(req, resp);
        }else{
            //返回XML格式
            req.setAttribute("videos", videos);
            req.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(req, resp);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}


 

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

<%@ 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"?>
<videonews> 
    <c:forEach items="${videos}" var="video">
        <news id="${video.id}">
            <title>${video.title}</title>
            <timelength>${video.timelength}</timelength> 
        </news>
    </c:forEach> 
</videonews>


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

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

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ListServlet</servlet-name>
    <servlet-class>cn.roco.servlet.ListServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ListServlet</servlet-name>
    <url-pattern>/ListServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


 


 

服務器端寫好之后,就開始寫Android應用

架構如下圖所示:

 

package cn.roco.news.domain;
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;
    }

}


 

package cn.roco.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StremTools {
    /**
     * 讀取輸入流中的數據
     * @param inputStream  輸入流
     * @return   二進制的流數據
     * @throws Exception
     */
    public static byte[] read(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int length=0;
        while((length=inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,length);
        }
        inputStream.close();
        return outputStream.toByteArray();
    }

}


 

package cn.roco.news.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 cn.roco.news.domain.News;
import cn.roco.utils.StremTools;

public class VideoNewsService {

    /**
     * 獲取最新的視頻資訊
     * 采用JSON格式
     * @param path
     * @return
     * @throws Exception
     */
    public static List<News> getJSONLastNews(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 基于HTTP協議連接對象
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            return parseJSON(inputStream);
        }else{
            throw new RuntimeException("服務器響應失敗");
        }
    }
    /**
     * 解析服務器返回的JSON數據
     * 
     * @param inputStream
     * @return
     * @throws Exception 
     */
    private static List<News> parseJSON(InputStream inputStream) throws Exception {
        List<News> newses=new ArrayList<News>();
        byte[] data=StremTools.read(inputStream);
        String jsonData=new String(data,"UTF-8");
        JSONArray array=new JSONArray(jsonData); 
        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 path
     * @return
     * @throws Exception
     */
    public static List<News> getLastNews(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 基于HTTP協議連接對象
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            return parseXML(inputStream);
        }
        return null;
    }

    /**
     * 解析服務器返回的XML數據
     * 
     * @param inputStream
     * @return
     */
    private static List<News> parseXML(InputStream inputStream) throws Exception {
        List<News> newses = new ArrayList<News>();
        News news = null;
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(inputStream, "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())) {
                    newses.add(news);
                    news = null;
                }
                break;
            }
            event = parser.next();
        }
        return newses;
    }
}

package cn.roco.news;

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

import cn.roco.news.domain.News;
import cn.roco.news.service.VideoNewsService;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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) findViewById(R.id.listView);
        try {
            //采用XML格式
//          String xmlPath="http://192.168.15.58:8080/Hello/ListServlet";
//          List<News> videos = VideoNewsService.getLastNews();

            //采用JSON格式
            String jsonPath="http://192.168.15.58:8080/Hello/ListServlet?format=json";
            List<News> videos = VideoNewsService.getJSONLastNews(jsonPath);

            List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            for (News news : videos) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put(
                        "timelength",
                        getResources().getString(R.string.timelength)
                                + news.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);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "有錯", 1);
            e.printStackTrace();
        }
    }
}


 item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/title" android:layout_width="200dp"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/timelength" android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>


main.xml

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

    <LinearLayout android:orientation="horizontal"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:text="@string/title" android:layout_width="200dp"
            android:layout_height="wrap_content" />
        <TextView android:text="@string/details" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

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

 

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">視頻資訊</string>
    <string name="timelength">時長:</string>
    <string name="min">分鐘</string>
    <string name="title">標題</string>
    <string name="details">詳情</string>
</resources>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="cn.roco.news"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
   <!-- 訪問Internet權限 -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

 

運行效果如圖所示:
 Android獲取服務器上格式為JSON和XML兩種格式的信息的小程序


 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!