现在的位置: 首页 > 综合 > 正文

Android开发入门之网络通信(资源客户端)

2017年04月01日 ⁄ 综合 ⁄ 共 7423字 ⁄ 字号 评论关闭

Web端:

News:

package cn.leigo.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;
    }

}


VideoNewsService:

package cn.leigo.service;

import java.util.List;

import cn.leigo.domain.News;

public interface VideoNewsService {

	/**
	 * 获取最新视频资源
	 * @return
	 */
	public List<News> getLastNews();

}

VideoNewsServiceImpl:

package cn.leigo.service.impl;

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

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

public class VideoNewsServiceImpl implements VideoNewsService {

	public List<News> getLastNews() {
		List<News> newses = new ArrayList<News>();
		newses.add(new News(12, "喜洋洋与灰太狼全集", 60));
		newses.add(new News(35, "实拍船载直升东海救援演习", 10));
		newses.add(new News(56, "喀麦隆VS荷兰", 40));
		return newses;
	}

}

ListServlet:

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

public class ListServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private VideoNewsService service = new VideoNewsServiceImpl();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<News> videos = service.getLastNews();
		request.setAttribute("videos", videos);
		request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
	}
}

<%@ page language="java" contentType="text/xml; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib
	uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><?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>

运行:

Android客户端:

News:

package cn.leigo.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;
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", timelength="
				+ timelength + "]";
	}

}

VideoNewsService:

package cn.leigo.service;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;
import cn.leigo.domain.News;

public class VideoNewsService {

	/**
	 * 获取最新的视频资讯
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	public static List<News> getLastNews() throws IOException, XmlPullParserException {
		String path = "http://192.168.1.100:8080/videonews/ListServlet";
		List<News> videonews = new ArrayList<News>();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream inputStream = conn.getInputStream();
			videonews = parseXML(inputStream);
		}
		return videonews;
	}

	/**
	 * 解析服务器返回的xml数据
	 * @param inputStream
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public static List<News> parseXML(InputStream inputStream)
			throws XmlPullParserException, IOException {
		List<News> videonews = null;
		News news = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inputStream, "UTF-8");
		int eventType = parser.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_TAG:
				if ("videonews".equals(parser.getName())) {
					videonews = new ArrayList<News>();
				} else if ("news".equals(parser.getName())) {
					news = new News();
					news.setId(Integer.parseInt(parser.getAttributeValue(0)));
				} else if ("title".equals(parser.getName())) {
					news.setTitle(parser.nextText());
				} else if ("timelength".equals(parser.getName())) {
					news.setTimelength(Integer.parseInt(parser.nextText()));
				}
				break;
			case XmlPullParser.END_TAG:
				if ("news".equals(parser.getName())) {
					videonews.add(news);
					news = null;
				}
				break;
			default:
				break;
			}
			eventType = parser.next();
		}
		return videonews;
	}
}

MainActivity:

package cn.leigo.news;

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

import org.xmlpull.v1.XmlPullParserException;

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

public class MainActivity extends Activity {
	private ListView mNewsListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mNewsListView = (ListView) findViewById(R.id.lv_news);
		List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		List<News> videos;
		try {
			videos = VideoNewsService.getLastNews();
			for (News news : videos) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("title", news.getTitle());
				map.put("timelength",
						getResources().getString(R.string.timelength)
								+ news.getTimelength()
								+ getResources().getString(R.string.min));
				data.add(map);
			}

			SimpleAdapter adapter = new SimpleAdapter(this, data,
					R.layout.item, new String[] { "title", "timelength" },
					new int[] { R.id.tv_title, R.id.tv_timelength });
			mNewsListView.setAdapter(adapter);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}

	}
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lv_news" />

</RelativeLayout>

item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />

    <TextView
        android:id="@+id/tv_timelength"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

</RelativeLayout>

strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">视频资讯</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="timelength">时长:</string>
    <string name="min">分钟</string>

</resources>

    <uses-permission android:name="android.permission.INTERNET"/>

抱歉!评论已关闭.