原文出自

参考网址(重要)

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)代码如下

[java] 
view plain
copy

 

  1. package com.quickmanager.util;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.FileInputStream;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import javax.xml.parsers.DocumentBuilder;
  11. import javax.xml.parsers.DocumentBuilderFactory;
  12. import javax.xml.parsers.ParserConfigurationException;
  13. import org.w3c.dom.Document;
  14. import org.w3c.dom.Element;
  15. import org.w3c.dom.Node;
  16. import org.w3c.dom.NodeList;
  17. import org.xml.sax.SAXException;
  18. /**
  19. * 解析xml文档,包括本地文档和url
  20. * @author cyxl
  21. * @version 1.0 2012-05-24
  22. * @since 1.0
  23. *
  24. */
  25. public class XmlParser {
  26. InputStream inStream;
  27. Element root;
  28. public InputStream getInStream() {
  29. return inStream;
  30. }
  31. public void setInStream(InputStream inStream) {
  32. this.inStream = inStream;
  33. }
  34. public Element getRoot() {
  35. return root;
  36. }
  37. public void setRoot(Element root) {
  38. this.root = root;
  39. }
  40. public XmlParser() {
  41. }
  42. public XmlParser(InputStream inStream) {
  43. if (inStream != null) {
  44. this.inStream = inStream;
  45. DocumentBuilderFactory domfac = DocumentBuilderFactory
  46. .newInstance();
  47. try {
  48. DocumentBuilder domBuilder = domfac.newDocumentBuilder();
  49. Document doc = domBuilder.parse(inStream);
  50. root = doc.getDocumentElement();
  51. } catch (ParserConfigurationException e) {
  52. e.printStackTrace();
  53. } catch (SAXException e) {
  54. e.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. public XmlParser(String path) {
  61. InputStream inStream = null;
  62. try {
  63. inStream = new FileInputStream(path);
  64. } catch (FileNotFoundException e1) {
  65. e1.printStackTrace();
  66. }
  67. if (inStream != null) {
  68. this.inStream = inStream;
  69. DocumentBuilderFactory domfac = DocumentBuilderFactory
  70. .newInstance();
  71. try {
  72. DocumentBuilder domBuilder = domfac.newDocumentBuilder();
  73. Document doc = domBuilder.parse(inStream);
  74. root = doc.getDocumentElement();
  75. } catch (ParserConfigurationException e) {
  76. e.printStackTrace();
  77. } catch (SAXException e) {
  78. e.printStackTrace();
  79. } catch (IOException e) {
  80. e.printStackTrace();
  81. }
  82. }
  83. }
  84. public XmlParser(URL url) {
  85. InputStream inStream = null;
  86. try {
  87. inStream = url.openStream();
  88. } catch (IOException e1) {
  89. e1.printStackTrace();
  90. }
  91. if (inStream != null) {
  92. this.inStream = inStream;
  93. DocumentBuilderFactory domfac = DocumentBuilderFactory
  94. .newInstance();
  95. try {
  96. DocumentBuilder domBuilder = domfac.newDocumentBuilder();
  97. Document doc = domBuilder.parse(inStream);
  98. root = doc.getDocumentElement();
  99. } catch (ParserConfigurationException e) {
  100. e.printStackTrace();
  101. } catch (SAXException e) {
  102. e.printStackTrace();
  103. } catch (IOException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. }
  108. /**
  109. *
  110. * @param nodes
  111. * @return 单个节点多个值以分号分隔
  112. */
  113. public Map<String, String> getValue(String[] nodes) {
  114. if (inStream == null || root==null) {
  115. return null;
  116. }
  117. Map<String, String> map = new HashMap<String, String>();
  118. // 初始化每个节点的值为null
  119. for (int i = 0; i < nodes.length; i++) {
  120. map.put(nodes[i], null);
  121. }
  122. // 遍历第一节点
  123. NodeList topNodes = root.getChildNodes();
  124. if (topNodes != null) {
  125. for (int i = 0; i < topNodes.getLength(); i++) {
  126. Node book = topNodes.item(i);
  127. if (book.getNodeType() == Node.ELEMENT_NODE) {
  128. for (int j = 0; j < nodes.length; j++) {
  129. for (Node node = book.getFirstChild(); node != null; node = node
  130. .getNextSibling()) {
  131. if (node.getNodeType() == Node.ELEMENT_NODE) {
  132. if (node.getNodeName().equals(nodes[j])) {
  133. //String val=node.getFirstChild().getNodeValue();
  134. String val = node.getTextContent();
  135. System.out.println(nodes[j] + ":" + val);
  136. // 如果原来已经有值则以分号分隔
  137. String temp = map.get(nodes[j]);
  138. if (temp != null && !temp.equals("")) {
  139. temp = temp + ";" + val;
  140. } else {
  141. temp = val;
  142. }
  143. map.put(nodes[j], temp);
  144. }
  145. }
  146. }
  147. }
  148. }
  149. }
  150. }
  151. return map;
  152. }
  153. }

4)测试代码如下

[java] 
view plain
copy

 

  1. public static void main(String[] args) {
  2. String link = "http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0";
  3. URL url;
  4. String path = "test.xml";
  5. try {
  6. url = new URL(link);
  7. System.out.println(url);
  8. // InputStream inStream= url.openStream();
  9. // InputStream inStream=new FileInputStream(new File("test.xml"));
  10. XmlParser parser = new XmlParser(url);
  11. String[] nodes = {"status1","temperature1","temperature2"};
  12. Map<String, String> map = parser.getValue(nodes);
  13. System.out.println(map.get(nodes[0]));
  14. } catch (MalformedURLException e) {
  15. e.printStackTrace();
  16. }
  17. }

5)输出结果

[plain] 
view plain
copy

 

  1. http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0
  2. status1:阵雨
  3. temperature1:21
  4. temperature2:18
  5. 阵雨

6)说明。改类的主要方法为getValue,传入的参数一个节点名字数组。具体可以参考测试代码,测试代码中我们获取了天气、最低温度和最高温度三项。构造方法重载了三种方式,第一种为直接传入字符流,第二种为传入本地xml文档的路径,第三种为传入一个URL对象,我们获取天气时就是采用了第三种方式,因为我们是从互联网上获取的一个页面数据

附加:最近在浏览CSDN时发现另外有篇文章获取天气信息的。感觉还是挺方便的,在这里分享一下:http://blog.csdn.net/hello_haozi/article/details/7564223

根据新浪天气API获取各地天气状况(Java实现)的更多相关文章

  1. 使用新浪IP库获取IP详细地址

    使用新浪IP库获取IP详细地址 <?php class Tool{ /** * 获取IP的归属地( 新浪IP库 ) * * @param $ip String IP地址:112.65.102.1 ...

  2. 新浪新闻API

    新浪新闻API ustcmio 关注 2017.01.15 20:44* 字数 536 阅读 2479评论 2喜欢 7 新浪新闻的API:1.访问手机新浪网https://sina.cn/?from= ...

  3. 使用小米天气API获取天气信息

    1. URL部分 以下url中"%s"代表的是城市Id,比如北京的cityId=101010100: //获取未来五天预报信息,红色部分信息不需要 WEATHER_DATA_URL ...

  4. 新浪通过API分享 实践

    注:如果集成了百度的Frontia和SinaCoreSDK, 那么SSO会出现包冲突 https://github.com/sinaweibosdk/weibo_android_sdk/issues/ ...

  5. [threeJs][新浪股票api][css3]3D新浪财经数据-最近A股涨的也太疯了......

    使用threeJS搭配新浪股票财经API 在线: http://wangxinsheng.herokuapp.com/stock 截图: A股涨幅榜[一片红10%] 检索[单击添加到自选内,自选使用l ...

  6. curl实例-通过新浪股票接口获取股票信息

    在学习curl的过程中,我们知道curl是相当于一个简单的浏览器,通过往对应的服务上面发送数据信息,返回服务器的响应结果,这个在Java里面主要是使用封装好的httpclient来进行操作,但是自己认 ...

  7. 新浪 股票 API

    新浪期货数据接口 [例子]http://hq.sinajs.cn/list=M0豆粕连续 M0 返回值如下:var hq_str_M0="豆粕连续,145958,3170,3190,3145 ...

  8. 新浪新闻API接口

    头条 http://api.sina.cn/sinago/list.json?channel=news_toutiao推荐 http://api.sina.cn/sinago/list.json?ch ...

  9. scrapy新浪天气

    一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到桌面上的程序: LX终端(LXTermin ...

随机推荐

  1. 每天一条linux命令——login

    login命令用于给出登录界面,可用于重新登录或者切换用户身份,也可通过它的功能随时更换登入身份.当/etc/nologin文件存在时,系统只root帐号登入系统,其他用户一律不准登入. 语法: lo ...

  2. select、poll、epoll用法

    我们先从著名的C10K问题开始探讨,由于早期在网络还不普及的时候,互联网的用户并不是很多,一台服务器同时在线100个用户估计在当时已经算是大型应用了.但是随着互联网的发展,用户群体迅速的扩大,每一个用 ...

  3. 简明Vim练级攻略

    原文:酷壳网 vim的学习曲线相当的大(参看各种文本编辑器的学习曲线),所以,如果你一开始看到的是一大堆VIM的命令分类,你一定会对这个编辑器失去兴趣的.下面的文章翻译自<Learn Vim P ...

  4. chromedriver release note

    ----------ChromeDriver v2.25 (2016-10-25)---------- Supports Chrome v53-55 Resolved issue 1547: Chro ...

  5. 关于使用iframe标签自适应高度的使用

    在ifrome内设定最小高度,(此方法只适用于页面内切换高度不一.但是会保留最大高度,返回后保持最大高度不再回到最初页面的高度) <iframe id="one4" widt ...

  6. photoshop cc 版本安装失败解决办法

    好久没有碰ps,看了下在ps版本都到cc了.忍不住也想尝试最新版本,但是安装出现了很多问题,导致我花了很多时间才搞定,现在分享给大家几点经验吧. Exit Code: Please see speci ...

  7. ie8 background css没有显示?——都是空格惹的祸

    ie8 background css没有显示?——都是空格惹的祸

  8. 浏览器JS报错Uncaught RangeError: Maximum call stack size exceeded?

    JavaScript错误:Uncaught RangeError: Maximum call stack size exceeded 堆栈溢出 原因:有小类到大类的递归查询导致溢出 解决方法思想: A ...

  9. highcharts实例教程二:结合php与mysql生成饼图

    上回我们分析了用highcharts结合php和mysql生成折线图的实例,这次我们以技术cto网站搜索引擎流量为例利用highcharts生成饼图. 饼图通常用在我们需要直观地显示各个部分所占的比例 ...

  10. windows下实现uboot的tftp下载功能

    一.原理分析 带有uboot的开发板实际上充当的就是tftp客户端,而PC机扮演的角色就是tftp服务器端,而tftp下载功能实际上就是文件传输.tftp服务器可以建立在虚拟机linux下,也可以建立 ...