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

简介:     首先写一个应用服务器端的jsp程序,用jsp和servlet简单实现,如下图所示     package cn.roco.domain;public class News { private Integer id; private...

 

 

首先写一个应用服务器端的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>

 

运行效果如图所示:
 


==================================================================================================

  作者:欧阳鹏  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址http://blog.csdn.net/ouyang_peng

==================================================================================================


 
相关文章
|
7月前
|
JSON 前端开发 应用服务中间件
配置Nginx根据IP地址进行流量限制以及返回JSON格式数据的方案
最后,记得在任何生产环境部署之前,进行透彻测试以确保一切运转如预期。遵循这些战术,守卫你的网络城堡不再是难题。
303 3
|
9月前
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
287 23
|
9月前
|
Go API 定位技术
MCP 实战:用 Go 语言开发一个查询 IP 信息的 MCP 服务器
随着 MCP 的快速普及和广泛应用,MCP 服务器也层出不穷。大多数开发者使用的 MCP 服务器开发库是官方提供的 typescript-sdk,而作为 Go 开发者,我们也可以借助优秀的第三方库去开发 MCP 服务器,例如 ThinkInAIXYZ/go-mcp。 本文将详细介绍如何在 Go 语言中使用 go-mcp 库来开发一个查询 IP 信息的 MCP 服务器。
540 0
|
12月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
JSON 人工智能 算法
探索大型语言模型LLM推理全阶段的JSON格式输出限制方法
本篇文章详细讨论了如何确保大型语言模型(LLMs)输出结构化的JSON格式,这对于提高数据处理的自动化程度和系统的互操作性至关重要。
1789 48
|
JSON JavaScript Java
对比JSON和Hessian2的序列化格式
通过以上对比分析,希望能够帮助开发者在不同场景下选择最适合的序列化格式,提高系统的整体性能和可维护性。
446 3
|
JSON API 数据安全/隐私保护
拍立淘按图搜索API接口返回数据的JSON格式示例
拍立淘按图搜索API接口允许用户通过上传图片来搜索相似的商品,该接口返回的通常是一个JSON格式的响应,其中包含了与上传图片相似的商品信息。以下是一个基于淘宝平台的拍立淘按图搜索API接口返回数据的JSON格式示例,同时提供对其关键字段的解释
|
JSON 数据格式 索引
Python中序列化/反序列化JSON格式的数据
【11月更文挑战第4天】本文介绍了 Python 中使用 `json` 模块进行序列化和反序列化的操作。序列化是指将 Python 对象(如字典、列表)转换为 JSON 字符串,主要使用 `json.dumps` 方法。示例包括基本的字典和列表序列化,以及自定义类的序列化。反序列化则是将 JSON 字符串转换回 Python 对象,使用 `json.loads` 方法。文中还提供了具体的代码示例,展示了如何处理不同类型的 Python 对象。
568 1
|
8月前
|
Android开发 开发者
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
本文详细介绍了如何通过自定义 `attrs.xml` 文件实现 Android 自定义 View 的属性配置。以一个包含 TextView 和 ImageView 的 DemoView 为例,讲解了如何使用自定义属性动态改变文字内容和控制图片显示隐藏。同时,通过设置布尔值和点击事件,实现了图片状态的切换功能。代码中展示了如何在构造函数中解析自定义属性,并通过方法 `setSetting0n` 和 `setbackeguang` 实现功能逻辑的优化与封装。此示例帮助开发者更好地理解自定义 View 的开发流程与 attrs.xml 的实际应用。
231 2
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
|
XML 前端开发 Java
讲解SSM的xml文件
本文详细介绍了SSM框架中的xml配置文件,包括springMVC.xml和applicationContext.xml,涉及组件扫描、数据源配置、事务管理、MyBatis集成以及Spring MVC的视图解析器配置。
303 1