通过新浪天气API获取天气

1.思路

通过上一篇获取位置后,获取天气情况。

2.代码如下

package com.xiang;

/**
 * java获取新浪天气预报代码
 */
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 解析xml文档,包括本地文档和url
 * 
 */
public class Weather {

	InputStream inStream;

	Element root;

	public InputStream getInStream() {

		return inStream;

	}

	public void setInStream(InputStream inStream) {

		this.inStream = inStream;

	}

	public Element getRoot() {

		return root;

	}

	public void setRoot(Element root) {

		this.root = root;

	}

	public Weather() {

	}

	/**
	 * 通过输入流来获取新浪接口信息
	 * 
	 * @param inStream
	 */
	public Weather(InputStream inStream) {

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	public Weather(String path) {

		InputStream inStream = null;

		try {

			inStream = new FileInputStream(path);

		} catch (FileNotFoundException e1) {

			e1.printStackTrace();

		}

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	public Weather(URL url) {

		InputStream inStream = null;

		try {

			inStream = url.openStream();

		} catch (IOException e1) {

			e1.printStackTrace();

		}

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	/**
	 * 
	 * @param nodes
	 * @return 单个节点多个值以分号分隔
	 */
	public Map<String, String> getValue(String[] nodes) {

		if (inStream == null || root == null) {

			return null;

		}

		Map<String, String> map = new HashMap<String, String>();

		// 初始化每个节点的值为null
		for (int i = 0; i < nodes.length; i++) {

			map.put(nodes[i], null);

		}

		// 遍历第一节点
		NodeList topNodes = root.getChildNodes();

		if (topNodes != null) {

			for (int i = 0; i < topNodes.getLength(); i++) {

				Node book = topNodes.item(i);

				if (book.getNodeType() == Node.ELEMENT_NODE) {

					for (int j = 0; j < nodes.length; j++) {

						for (Node node = book.getFirstChild(); node != null; node = node
								.getNextSibling()) {

							if (node.getNodeType() == Node.ELEMENT_NODE) {

								if (node.getNodeName().equals(nodes[j])) {

									String val = node.getTextContent();

									String temp = map.get(nodes[j]);

									if (temp != null && !temp.equals("")) {

										temp = temp + ";" + val;

									} else {

										temp = val;

									}

									map.put(nodes[j], temp);

								}
							}
						}
					}
				}
			}
		}
		return map;
	}

	public static void main(String[] args) {
		String cityString = null;
		try {
			cityString = URLEncoder.encode("青岛", "GBK");//此处改为获取的位置
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String link = "http://php.weather.sina.com.cn/xml.php?city="
				+ cityString + "&password=DJOYnieT8234jlsK&day=0";
		//System.out.println(link);
		URL url;

		try {
			url = new URL(link);
			Weather parser = new Weather(url);
			String[] nodes = { "city", "status1", "temperature1", "direction1",
					"power1", "status2", "temperature2", "direction2", "power2", "chy_shuoming", "gm_s", "yd_s", };
			Map<String, String> map = parser.getValue(nodes);
			System.out.println(map.get(nodes[0]) + ",今天白天:" + map.get(nodes[1])
					+ ",温度:" + map.get(nodes[2]) + "℃,风向:" + map.get(nodes[3])
					+ ",风级:" + map.get(nodes[4]) + ",今天夜间:" + map.get(nodes[5])
					+ ",温度:" + map.get(nodes[6]) + "℃,风向:" + map.get(nodes[7])
					+ ",风级:" + map.get(nodes[8]) + ",穿衣说明:" + map.get(nodes[9]) + ",感冒说明:" + map.get(nodes[10])
					+ ",运动说明:" + map.get(nodes[11]));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}

3.运行结果


4.更多参考


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值