Android獲取網絡XML/JSON數據

源碼轉自傳智播客

Video.java

package cn.itcast.domain;

public class Video {
	private Integer id;
	private String title;
	private Integer time;
	
	public Video(){}
	
	public Video(Integer id, String title, Integer time) {
		this.id = id;
		this.title = title;
		this.time = time;
	}
	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 getTime() {
		return time;
	}
	public void setTime(Integer time) {
		this.time = time;
	}
	
}


StreamTool.java

package cn.itcast.utils;

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

public class StreamTool {

	/**
	 * 從輸入流中獲取數據
	 * @param inStream 輸入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}


VideoService.java

package cn.itcast.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.itcast.domain.Video;
import cn.itcast.utils.StreamTool;

public class VideoService {
	/**
	 * 獲取最新的視頻資訊
	 * @return
	 * @throws Exception
	 */
	public static List<Video> getLastVideos() throws Exception{
		String path = "http://192.168.1.100:8080/videoweb/video/list.do";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		return parseXML(inStream);
	}
	
	public static List<Video> getJSONLastVideos() throws Exception{
		List<Video> videos = new ArrayList<Video>();
		String path = "http://192.168.1.100:8080/videoweb/video/list.do?format=json";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		byte[] data = StreamTool.readInputStream(inStream);
		String json = new String(data);
		JSONArray array = new JSONArray(json);
		for(int i=0 ; i < array.length() ; i++){
			JSONObject item = array.getJSONObject(i);
			int id = item.getInt("id");
			String title = item.getString("title");
			int timelength = item.getInt("timelength");
			videos.add(new Video(id, title, timelength));
		}
		return videos;
	}
	/**
	 * 解析服務器返回的協議,得到視頻資訊
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	private static List<Video> parseXML(InputStream inStream) throws Exception{
		List<Video> videos = null;
		Video video = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inStream, "UTF-8");
		int eventType = parser.getEventType();//產生第一個事件
		while(eventType!=XmlPullParser.END_DOCUMENT){//只要不是文檔結束事件
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				videos = new ArrayList<Video>();
				break;
	
			case XmlPullParser.START_TAG:
				String name = parser.getName();//獲取解析器當前指向的元素的名稱
				if("video".equals(name)){
					video = new Video();
					video.setId(new Integer(parser.getAttributeValue(0)));
				}
				if(video!=null){
					if("title".equals(name)){
						video.setTitle(parser.nextText());//獲取解析器當前指向元素的下一個文本節點的值
					}
					if("timelength".equals(name)){
						video.setTime(new Integer(parser.nextText()));
					}
				}
				break;
				
			case XmlPullParser.END_TAG:
				if("video".equals(parser.getName())){
					videos.add(video);
					video = null;
				}
				break;
			}
			eventType = parser.next();
		}
		return videos;
	}
}


MainActivity.java

package cn.itcast.videoclient;

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

import cn.itcast.domain.Video;
import cn.itcast.service.VideoService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    private ListView listView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        listView = (ListView)this.findViewById(R.id.listView);
        try {
			List<Video> videos = VideoService.getJSONLastVideos();
			List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
			for(Video video : videos){
				HashMap<String, Object> item = new HashMap<String, Object>();
				item.put("id", video.getId());
				item.put("title", video.getTitle());
				item.put("timelength", "時長:"+ video.getTime());
				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(MainActivity.this, "獲取最新視頻資訊失敗", 1).show();
			Log.e("MainActivity", e.toString());
		} 
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章