根据新浪天气API获取各地天气状况(Java实现)
原文出自
参考网址(重要)
http://blog.csdn.net/cyxlzzs/article/details/7602469 新浪
http://blog.csdn.net/l_ch_g/article/details/8205817 新浪
http://blog.csdn.net/killtl/article/details/7312514 新浪
http://blog.csdn.net/qq910894904/article/details/7540093 新浪
http://blog.sina.com.cn/s/blog_417845750101d5ws.html 国家气象局
http://www.verydemo.com/demo_c131_i42456.html 国家气象局
http://blog.csdn.net/hello_haozi/article/details/7564223 国家气象局
http://www.oschina.net/code/snippet_96894_17983 中国天气网api
1、很多时候我们会需要在自己的应用上面显示天气状况,这种情况我们只能借助第三方的API来进行实现
2、这里我们讲一下如何获取新浪API提供的天气
1)首先我们在浏览器中访问地址“http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0”。这时我们看到的是一个关于重庆的天气状况的一个xml文档。仔细观察该地址,我们发现如果我们要查看其它城市的天气时只要将city后面的参数换成你想要的城市,也许你会认为city的值怎么是一推看不懂的字符,如果你在百度一下框中输入重庆两个字后点击按钮后你会发现url变成了“http://www.baidu.com/s?wd=%D6%D8%C7%EC&rsv_bp=0&rsv_spt=3&inputT=2574”,比对一下wd参数值就可以知道,它就是重庆两个字的另一种编码方式
2)好了,现在我们得到了某个城市天气状况的xml文档,我们想要得到我们的天气描述主要解析该文档就好了,接下来我们就编码实现java解析xml文档
3)代码如下
- package com.quickmanager.util;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.FileInputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- 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
- * @author cyxl
- * @version 1.0 2012-05-24
- * @since 1.0
- *
- */
- public class XmlParser {
- 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 XmlParser() {
- }
- public XmlParser(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 XmlParser(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 XmlParser(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.getFirstChild().getNodeValue();
- String val = node.getTextContent();
- System.out.println(nodes[j] + ":" + val);
- // 如果原来已经有值则以分号分隔
- String temp = map.get(nodes[j]);
- if (temp != null && !temp.equals("")) {
- temp = temp + ";" + val;
- } else {
- temp = val;
- }
- map.put(nodes[j], temp);
- }
- }
- }
- }
- }
- }
- }
- return map;
- }
- }
4)测试代码如下
- public static void main(String[] args) {
- String link = "http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0";
- URL url;
- String path = "test.xml";
- try {
- url = new URL(link);
- System.out.println(url);
- // InputStream inStream= url.openStream();
- // InputStream inStream=new FileInputStream(new File("test.xml"));
- XmlParser parser = new XmlParser(url);
- String[] nodes = {"status1","temperature1","temperature2"};
- Map<String, String> map = parser.getValue(nodes);
- System.out.println(map.get(nodes[0]));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
5)输出结果
- http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0
- status1:阵雨
- temperature1:21
- temperature2:18
- 阵雨
6)说明。改类的主要方法为getValue,传入的参数一个节点名字数组。具体可以参考测试代码,测试代码中我们获取了天气、最低温度和最高温度三项。构造方法重载了三种方式,第一种为直接传入字符流,第二种为传入本地xml文档的路径,第三种为传入一个URL对象,我们获取天气时就是采用了第三种方式,因为我们是从互联网上获取的一个页面数据
附加:最近在浏览CSDN时发现另外有篇文章获取天气信息的。感觉还是挺方便的,在这里分享一下:http://blog.csdn.net/hello_haozi/article/details/7564223
根据新浪天气API获取各地天气状况(Java实现)的更多相关文章
- 使用新浪IP库获取IP详细地址
使用新浪IP库获取IP详细地址 <?php class Tool{ /** * 获取IP的归属地( 新浪IP库 ) * * @param $ip String IP地址:112.65.102.1 ...
- 新浪新闻API
新浪新闻API ustcmio 关注 2017.01.15 20:44* 字数 536 阅读 2479评论 2喜欢 7 新浪新闻的API:1.访问手机新浪网https://sina.cn/?from= ...
- 使用小米天气API获取天气信息
1. URL部分 以下url中"%s"代表的是城市Id,比如北京的cityId=101010100: //获取未来五天预报信息,红色部分信息不需要 WEATHER_DATA_URL ...
- 新浪通过API分享 实践
注:如果集成了百度的Frontia和SinaCoreSDK, 那么SSO会出现包冲突 https://github.com/sinaweibosdk/weibo_android_sdk/issues/ ...
- [threeJs][新浪股票api][css3]3D新浪财经数据-最近A股涨的也太疯了......
使用threeJS搭配新浪股票财经API 在线: http://wangxinsheng.herokuapp.com/stock 截图: A股涨幅榜[一片红10%] 检索[单击添加到自选内,自选使用l ...
- curl实例-通过新浪股票接口获取股票信息
在学习curl的过程中,我们知道curl是相当于一个简单的浏览器,通过往对应的服务上面发送数据信息,返回服务器的响应结果,这个在Java里面主要是使用封装好的httpclient来进行操作,但是自己认 ...
- 新浪 股票 API
新浪期货数据接口 [例子]http://hq.sinajs.cn/list=M0豆粕连续 M0 返回值如下:var hq_str_M0="豆粕连续,145958,3170,3190,3145 ...
- 新浪新闻API接口
头条 http://api.sina.cn/sinago/list.json?channel=news_toutiao推荐 http://api.sina.cn/sinago/list.json?ch ...
- scrapy新浪天气
一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到桌面上的程序: LX终端(LXTermin ...
随机推荐
- QT QSettings 操作(导入导出、保存获取信息)*.ini文件详解
1.QSettings基本使用 1.1.生成.ini文件,来点实用的代码吧. QString fileName;fileName = QCoreApplication::applicationDirP ...
- 做了一个类似天猫鼠标经过icon的动画,记录一下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 在easyui dialog的子页面内如何关闭弹窗
因项目需要在dialog中添加滚动条,所以就在div中加了iframe: <div id="applyRefundDialog" style="display:no ...
- Android单元测试初探——Instrumentation(转载)
学习Android有一段时间了,虽然前段时间对软件测试有了一些了解,不过接触android的单元测试却是头一次.这几天在物流大赛上也用了不少时间,所以对于android的单元测试没有太深入的研究,所以 ...
- CSS3的appearance属性--改变元素的外观
CSS3 appearance 属性 CSS 参考手册 实例 使 div 元素看上去像一个按钮: div { appearance:button; -moz-appearance:button; /* ...
- spoj SORTBIT - Sorted bit squence
Let's consider the 32 bit representation of all integers i from m up to n inclusive (m ≤ i ≤ n; m × ...
- 【Java】对服务器程序的理解
Login:------------->方法 Data:----->类.API数据 Collection:-------->集合 Data Source File: Database ...
- Dungeon Master(poj 2251)
Description You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is co ...
- Struts2 权限验证
之前的Struts2项目通过再Sitemesh的母版页中使用Struts的if标签进行了session判断,使得未登录的用户不能看到页面,但是这 种现仅仅在view层进行,如果未登录用户直接在地址栏输 ...
- 在InnoDB,记录在 non-clustered indexes(也被称为secondary indexes) 包含了主键值
In InnoDB, the records in non-clustered indexes (also called secondary indexes) contain the primary ...