百度天气预报API的使用(java版本)

0 篇文章 0 订阅



要使用百度天气预报api,首先要有密钥ak,申请地址http://developer.baidu.com/map/lbs-cloud.htm

然后向http://api.map.baidu.com/telematics/v3/weather?location=郑州&output=xml&ak=A72e372de05e63c8740b2622d0ed8ab1
请求,然后会返还给你一个xml文档格式的天气预报如下:

XML代码 
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <CityWeatherResponse>
  3.   <status>success</status>
  4.   <date>2014-04-29</date>
  5.   <results>
  6.     <currentCity>郑州</currentCity>
  7.     <weather_data>
  8.           <date>周二(今天, 实时:20℃)</date>
  9.       <dayPictureUrl>http://api.map.baidu.com/images/weather/day/qing.png<;/dayPictureUrl>
  10.       <nightPictureUrl>http://api.map.baidu.com/images/weather/night/qing.png<;/nightPictureUrl>
  11.       <weather>晴</weather>
  12.       <wind>微风</wind>
  13.       <temperature>13℃</temperature>
  14.           <date>周三</date>
  15.       <dayPictureUrl>http://api.map.baidu.com/images/weather/day/qing.png<;/dayPictureUrl>
  16.       <nightPictureUrl>http://api.map.baidu.com/images/weather/night/qing.png<;/nightPictureUrl>
  17.       <weather>晴</weather>
  18.       <wind>微风</wind>
  19.       <temperature>28 ~ 15℃</temperature>
  20.           <date>周四</date>
  21.       <dayPictureUrl>http://api.map.baidu.com/images/weather/day/duoyun.png<;/dayPictureUrl>
  22.       <nightPictureUrl>http://api.map.baidu.com/images/weather/night/yin.png<;/nightPictureUrl>
  23.       <weather>多云转阴</weather>
  24.       <wind>微风</wind>
  25.       <temperature>30 ~ 15℃</temperature>
  26.           <date>周五</date>
  27.       <dayPictureUrl>http://api.map.baidu.com/images/weather/day/yin.png<;/dayPictureUrl>
  28.       <nightPictureUrl>http://api.map.baidu.com/images/weather/night/duoyun.png<;/nightPictureUrl>
  29.       <weather>阴转多云</weather>
  30.       <wind>微风</wind>
  31.       <temperature>25 ~ 15℃</temperature>
  32.         </weather_data>
  33.     </results>
  34. </CityWeatherResponse>

接下 来只需要对此xml文档解析取出数据即可
具体代码如下:

Java代码 
  1. package com.ashen.testapi;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import org.dom4j.Document;
  12. import org.dom4j.DocumentException;
  13. import org.dom4j.DocumentHelper;
  14. import org.dom4j.Element;
  15. public class BaiduWeather {
  16.     //获取天气信息
  17.   public static String GetWeater(String city) {
  18.     BaiduWeather wu=new BaiduWeather();
  19.     String buffstr=null;
  20.     try {
  21.         String xml= wu.GetXmlCode(URLEncoder.encode(city, "utf-8"));  //设置输入城市的编码,以满足百度天气api需要
  22.         buffstr=wu.readStringXml(xml,city);//调用xml解析函数
  23.     } catch (Exception e) {
  24.     e.printStackTrace();
  25.     }
  26.     return  buffstr;
  27.     }
  28.     public String GetXmlCode(String city) throws UnsupportedEncodingException{
  29.     String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=xml&ak=A72e372de05e63c8740b2622d0ed8ab1";  
  30.     StringBuffer buffer = null;  
  31.     try {  
  32.     // 建立连接  
  33.     URL url = new URL(requestUrl);
  34.     HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
  35.     httpUrlConn.setDoInput(true);  
  36.     httpUrlConn.setRequestMethod("GET");  
  37.     // 获取输入流  
  38.     InputStream inputStream = httpUrlConn.getInputStream();  
  39.     InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
  40.     BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  41.     // 读取返回结果  
  42.     buffer = new StringBuffer();  
  43.     String str = null;  
  44.     while ((str = bufferedReader.readLine()) != null) {  
  45.       buffer.append(str);  
  46.     }  
  47.   
  48.     // 释放资源  
  49.     bufferedReader.close();  
  50.     inputStreamReader.close();  
  51.     inputStream.close();  
  52.     httpUrlConn.disconnect();  
  53.     } catch (Exception e) {  
  54.     e.printStackTrace();  
  55.     }  
  56.     return buffer.toString();  //返回获取的xml字符串
  57. }
  58. public String readStringXml(String xml,String ifcity) {
  59.   StringBuffer buff=new StringBuffer();  //用来拼接天气信息的
  60.   Document doc = null;
  61.   List listdate=null;  //用来存放日期
  62.   List listday=null;  //用来存放白天图片路径信息
  63.   List listweather=null;
  64.   List listwind=null;
  65.   List listtem=null;
  66.   try {
  67.     // 读取并解析XML文档
  68.     //下面的是通过解析xml字符串的
  69.     doc = DocumentHelper.parseText(xml); // 将字符串转为XML  
  70.     Element rootElt = doc.getRootElement(); // 获取根节点    
  71.     Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
  72.     String status=rootElt.elementText("status"); //获取状态,如果等于success,表示有数据
  73.     if(!status.equals("success"))
  74.       return "暂无数据";  //如果不存在数据,直接返回
  75.     String date= rootElt.elementText("date");  //获取根节点下的,当天日期
  76.     buff.append(date+"\n");
  77.     //遍历results节点
  78.       while (iter.hasNext()) {
  79.       Element recordEle = (Element) iter.next();
  80.       Iterator iters = recordEle.elementIterator("weather_data"); //
  81.     //遍历results节点下的weather_data节点
  82.       while (iters.hasNext()) {
  83.         Element itemEle = (Element) iters.next();  
  84.         listdate=itemEle.elements("date");
  85.       //将date集合放到listdate中
  86.         listday=itemEle.elements("dayPictureUrl");
  87.         listweather=itemEle.elements("weather");
  88.         listwind=itemEle.elements("wind");
  89.         listtem=itemEle.elements("temperature");
  90.     }
  91.     for(int i=0;i<listdate.size();i++){  //由于每一个list.size都相等,这里统一处理
  92.       Element eledate=(Element)listdate.get(i); //依次取出date
  93.       Element eleday=(Element)listday.get(i);//..
  94.       Element eleweather=(Element)listweather.get(i);
  95.       Element elewind=(Element)listwind.get(i);
  96.       Element eletem=(Element)listtem.get(i);            
  97.       buff.append(eledate.getText()+"==="+eleweather.getText()+"==="+elewind.getText()+"==="+eletem.getText()+"\n");  //拼接信息
  98.         //*****************如果想用到微信公众号上,还请自己继续写代码,我只能帮到这了,数据已经分离开了。
  99.       //微信天气处理  省略
  100.     }  
  101.     }
  102.     } catch (DocumentException e) {
  103.     e.printStackTrace();
  104.     } catch (Exception e) {
  105.     e.printStackTrace();
  106.     }
  107.     return buff.toString();  
  108. }
  109. public static void main(String[] args){
  110. //测试
  111. System.out.println(GetWeater("郑州").toString());
  112. }
  113. }

测试结果:
2014-04-29
周二(今天, 实时:20℃)===晴===微风===13℃
周三===晴===微风===28 ~ 15℃
周四===多云转阴===微风===30 ~ 15℃
周五===阴转多云===微风===25 ~ 15℃
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值