zoukankan      html  css  js  c++  java
  • [置顶] 获取服务器上格式为JSON和XML两种格式的信息的小程序

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

    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>

    运行效果如图所示:
     


     

  • 相关阅读:
    Java 5,6,7,8,9,10,11新特性
    LINUX中如何查看某个端口是否被占用
    Springboot项目全局异常统一处理
    面试笔记
    springboot几篇文章
    Mysql索引会失效的几种情况分析
    数组变成集合的方法
    集合变成数组的方法 Collections里面的方法
    list类里面的东西加锁 (手动加锁方法)
    Collections里面的一些方法
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2998298.html
Copyright © 2011-2022 走看看