android 解析网络xml数据,发送xml数据,解析json数据

video实体类 包含id title time字段  为这个demo提供网络数据的是自己写的一个j2ee工程,

主activity代码

package com.itcast.net_xml;

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

import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONException;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParserException;

import com.itcast.bean.Video;
import com.itcast.service.HttpRequestService;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";
	private Button jsonButton;
	private Button xmlButton;
	private ListView listView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		jsonButton = (Button) findViewById(R.id.jsonButton);
		xmlButton = (Button) findViewById(R.id.xmlButton);
		listView = (ListView) findViewById(R.id.listView);
		xmlButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, R.string.xmlButton, Toast.LENGTH_SHORT).show();
				String path = "http://192.168.1.110:8080/videoweb/xmlVideos";// 获取数据的地址
				try {
					List<Video> videos = null;
					videos = HttpRequestService.getXMLVideos(path);
					List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
					for (Video video : videos) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("id", video.getId());
						map.put("title", video.getTitle());
						map.put("time", video.getTime());
						data.add(map);
					}
					SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.item, new String[] { "title",
							"time" }, new int[] { R.id.title, R.id.time });
					listView.setAdapter(adapter);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
					Log.i(TAG, e.toString());
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i(TAG, e.toString());
					Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
				}

			}
		});
		jsonButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, R.string.jsonButton, Toast.LENGTH_SHORT).show();
				String path = "http://192.168.1.110:8080/videoweb/jsonVideos";
				try {
					List<Video> videos = HttpRequestService.getJSONVideos(path);
					List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
					for (Video video : videos) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("id", video.getId());
						map.put("title", video.getTitle());
						map.put("time", video.getTime());
						data.add(map);
					}
					SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.item, new String[] { "title",
							"time" }, new int[] { R.id.title, R.id.time });
					listView.setAdapter(adapter);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
					Log.i(TAG, e.toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i(TAG, e.toString());
					Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}


 主要业务和解析过程代码

package com.itcast.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.itcast.bean.Video;
import com.itcast.util.StreamTool;

public class HttpRequestService {
	/**
	 * 获取xml数据
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	public static List<Video> getXMLVideos(String path) throws IOException, XmlPullParserException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 打开数据连接
		conn.setReadTimeout(5 * 1000);
		conn.setRequestMethod("GET");// 必须要大写
		InputStream inputStream = conn.getInputStream();// 获取请求的数据流
		return paseXML(inputStream);// 解析
	}

	/**
	 * pull解析xml
	 * 
	 * @param inputStream
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public static List<Video> paseXML(InputStream inputStream) throws XmlPullParserException, IOException {
		Video video = null;
		List<Video> videos = null;
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(inputStream, "UTF-8");
		int event = pullParser.getEventType();// 解析后执行事件的Code
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:// 解析文档的开始,可初始化值
				videos = new ArrayList<Video>();
				break;
			case XmlPullParser.START_TAG:// 解析析元素的开始
				String name = pullParser.getName();
				if ("video".equalsIgnoreCase(name)) {
					video = new Video();
					// 解析的时候做好吧两百的空格去掉,有的会在文本的开始前加空格,这样就没法转成int类型,而且数据还会有错误
					video.setId(Integer.parseInt(pullParser.getAttributeValue(0).trim()));// 取得video元素中的id属性的值

				}
				if (video != null) {
					if ("title".equalsIgnoreCase(name)) {
						video.setTitle(pullParser.nextText().trim());// 取出titile元素的下一个文本节点的值,最好去空格
					} else if ("time".equalsIgnoreCase(name)) {
						video.setTime(Integer.parseInt(pullParser.nextText().trim()));
					}
				}
				break;
			case XmlPullParser.END_TAG:// 元素解析结束
				if ("video".equalsIgnoreCase(pullParser.getName())) {
					videos.add(video);
					video = null;
				}
				break;
			}
			event = pullParser.next();// 获取解析下一元素的事件代码,只要不是END_DOCUMENT(0),就表示它还在解析,那么继续循环
		}
		return videos;
	}

	/**
	 * 从服务器获取json格式的数据,并使用JSONArray类解析json
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public static List<Video> getJSONVideos(String path) throws IOException, JSONException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setRequestMethod("GET");// 必须要大写
		InputStream inputStream = (InputStream) conn.getInputStream();
		byte[] data = StreamTool.readInputStream(inputStream);
		JSONArray array = new JSONArray(new String(data));// json数据的封装类,这样就不用再解析json数据了
		List<Video> videos = new ArrayList<Video>();
		for (int i = 0; i < array.length(); i++) {
			JSONObject object = array.getJSONObject(i);
			Integer id = object.getInt("id");
			String title = object.getString("title");
			Integer time = object.getInt("time");
			videos.add(new Video(id, title, time));
		}
		return videos;
	}

	/**
	 * 发送xml文件到服务器
	 * 
	 * @param path
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static boolean sendXMLToWeb(String path, InputStream inputStream) throws IOException {
		byte[] data = StreamTool.readInputStream(inputStream);
		inputStream.close();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));
		OutputStream outStream = conn.getOutputStream();// 将xml的二进制数据写到流里
		outStream.write(data);
		outStream.flush();
		outStream.close();
		if (conn.getResponseCode() == 200) {// 判断返回的状态
			return true;
		} else {
			return false;
		}
	}
}


一个读取流的工具类

package com.itcast.util;

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

public class StreamTool {
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, len);
		}
		return outputStream.toByteArray();
	}
}


两个布局文件

主布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/xmlButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/xmlButton" />

        <Button
            android:id="@+id/jsonButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/jsonButton" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/title"
            android:layout_width="200dip"
            android:layout_height="wrap_content"
            android:text="标题"
            android:textSize="30dip" />

        <TextView
            android:id="@+id/time"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="时长"
            android:textSize="30dip" />
    </LinearLayout>

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

</LinearLayout>

 

listview布局文件

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

    <TextView
        android:id="@+id/title"
        android:layout_width="250dip"
        android:layout_height="wrap_content"
        android:textSize="20dip" />

    <TextView
        android:id="@+id/time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip" />

</LinearLayout>


 

 


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值