java调用天气预报案例

1.(出处)http://www.cnblogs.com/jason-star/archive/2012/09/25/2702032.html

2.找了老久的.终于在‘天边的星星’这位仁兄的博客发现,于是就

收藏了.非常感谢!
好多人要老问我,今天上代码,Copy到工程就用了JAVA调用天气预报服务WebService (webxml.com.cn网站提供)

package weather;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
public static String getYear(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String time = format.format(calendar.getTime());
return time;
}
}

 

 

package weather;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

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

public class weather {
private static String SERVICES_HOST = "www.webxml.com.cn";

private static String WEATHER_SERVICES_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/";

private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL
+ "getWeather?theUserID=&theCityCode=";

/**
* 城市代码 / 镇江: 1954
*/
private static int CITICODE = 1954;

public static void main(String[] args) throws Exception {
String desc = "今天是" +DateUtils.getYear() + ","
+ DateUtils.getWeekOfDate(new Date());
desc += new weather().getWeatherStr();
System.out.println(desc);
}

public InputStream getSoapInputStream(String url) {
InputStream inputStream = null;
try {
URL urlObj = new URL(url);
URLConnection urlConn = urlObj.openConnection();
urlConn.setRequestProperty("Host", SERVICES_HOST); // 具体webService相关
urlConn.connect();
inputStream = urlConn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}

public String getWeatherStr() {
String desc = "";
try {
List<String> weatherList = getWeather(CITICODE);

if (weatherList != null && weatherList.size() > 7) {
String tianqi = weatherList.get(7);
if (tianqi.contains("日")) {
tianqi = tianqi.substring(tianqi.indexOf("日") + 1);
}
String wendu = weatherList.get(8);
desc += ",天气" + tianqi;
desc += " ,";
desc += wendu.replace("℃", "度").replace("/", "--");
}
} catch (Exception e) {
e.printStackTrace();
return desc;
}
return desc;
}

public List<String> getWeather(int cityCode) {
List<String> weatherList = new ArrayList<String>();
Document document;
DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance();
documentBF.setNamespaceAware(true);
try {
DocumentBuilder documentB = documentBF.newDocumentBuilder();
InputStream inputStream = getSoapInputStream(WEATHER_QUERY_URL + cityCode);
document = documentB.parse(inputStream);
NodeList nl = document.getElementsByTagName("string");
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node n = nl.item(i);
String weather = n.getFirstChild().getNodeValue();
weatherList.add(weather);
}
inputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return weatherList;
}
}

 

下面是介绍

今天遇到的需求是显示一个“今天是星期五 2010年9月26日 天气晴,19-25度”这样的网站提示信息。

需要用到公共的天气预报webservice。

 

  1. /**   
  2. * 
  3. */ 
  4. public class WeatherService { 
  5.   private static String SERVICES_HOST = "www.webxml.com.cn"
  6.  
  7.   private static String WEATHER_SERVICES_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/"
  8.  
  9.   private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL + "getWeather?theUserID=&theCityCode="
  10.  
  11.   /** 
  12.    * 城市代码 / 武汉 
  13.    */ 
  14.   private static int CITICODE = 1582
  15.  
  16.   public static void main(String[] args) throws Exception { 
  17.     String desc = "今天是星期" + DateUtils.getCurrentWeek() + " " + DateUtils.getCurrent("yyyy年MM月dd日") + " "
  18.     desc += new WeatherService().getWeatherStr(); 
  19.     System.out.println(desc); 
  20.   } 
  21.  
  22.   public InputStream getSoapInputStream(String url) { 
  23.     InputStream inputStream = null
  24.     try { 
  25.       URL urlObj = new URL(url); 
  26.       URLConnection urlConn = urlObj.openConnection(); 
  27.       urlConn.setRequestProperty("Host", SERVICES_HOST); //具体webService相关 
  28.       urlConn.connect(); 
  29.       inputStream = urlConn.getInputStream(); 
  30.     } catch(MalformedURLException e) { 
  31.       e.printStackTrace(); 
  32.     } catch(IOException e) { 
  33.       e.printStackTrace(); 
  34.     } 
  35.     return inputStream; 
  36.   } 
  37.  
  38.   public String getWeatherStr() { 
  39.     String desc = ""
  40.     try { 
  41.       List<String> weatherList = getWeather(CITICODE); 
  42.  
  43.       if(weatherList != null && weatherList.size() > 7) { 
  44.         String tianqi = weatherList.get(7); 
  45.         if(tianqi.contains("日")) { 
  46.           tianqi = tianqi.substring(tianqi.indexOf("日") + 1); 
  47.         } 
  48.         String wendu = weatherList.get(8); 
  49.         desc += "天气" + tianqi; 
  50.         desc += " ,"
  51.         desc += wendu.replace("℃""度").replace("/""-"); 
  52.       } 
  53.     } catch(Exception e) { 
  54.       e.printStackTrace(); 
  55.       return desc; 
  56.     } 
  57.     return desc; 
  58.   } 
  59.  
  60.   public List<String> getWeather(int cityCode) { 
  61.     List<String> weatherList = new ArrayList<String>(); 
  62.     Document document; 
  63.     DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance(); 
  64.     documentBF.setNamespaceAware(true); 
  65.     try { 
  66.       DocumentBuilder documentB = documentBF.newDocumentBuilder(); 
  67.       InputStream inputStream = getSoapInputStream(WEATHER_QUERY_URL + cityCode); 
  68.       document = documentB.parse(inputStream); 
  69.       NodeList nl = document.getElementsByTagName("string"); 
  70.       int len = nl.getLength(); 
  71.       for(int i = 0; i < len; i++) { 
  72.         Node n = nl.item(i); 
  73.         String weather = n.getFirstChild().getNodeValue(); 
  74.         weatherList.add(weather); 
  75.       } 
  76.       inputStream.close(); 
  77.     } catch(UnsupportedEncodingException e) { 
  78.       e.printStackTrace(); 
  79.     } catch(DOMException e) { 
  80.       e.printStackTrace(); 
  81.     } catch(ParserConfigurationException e) { 
  82.       e.printStackTrace(); 
  83.     } catch(SAXException e) { 
  84.       e.printStackTrace(); 
  85.     } catch(IOException e) { 
  86.       e.printStackTrace(); 
  87.     } 
  88.     return weatherList; 
  89.   } 
  90.  

这里的citycode是城市代码,由于我只要用武汉的,这里已经定义好了,大家想找自己的城市,可以去这里查:

http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx

获得省份通过getRegionProvince,然后根据省IDgetSupportCityString获得CityCode 

说下程序:

这个服务的返回结果是xml,如下:

 

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <ArrayOfString xmlns="http://WebXml.com.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
  4.     <string>湖北</string> 
  5.     <string>武汉</string> 
  6.     <string>57494</string> 
  7.     <string>57494.jpg</string> 
  8.     <string>2012-7-11 16:32:58</string> 
  9.     <string>29℃/35℃</string> 
  10.     <string>7月11日 多云</string> 
  11.     <string>无持续风向微风</string> 
  12.     <string>1.gif</string> 
  13.     <string>1.gif</string> 
  14.     <string>今日天气实况:气温:34℃;风向/风力:西南风 3级;湿度:60%;空气质量:较差;紫外线强度:中等</string> 
  15.     <string>穿衣指数:天气炎热,建议着短衫、短裙、短裤、薄型T恤衫、敞领短袖棉衫等清凉夏季服装。 
  16.         感冒指数:各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。 
  17.         运动指数:天气较好,无雨水困扰,但考虑气温很高,请注意适当减少运动时间并降低运动强度,运动后补充水分。 
  18.         洗车指数:较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。 
  19.         晾晒指数:天气不错,适宜晾晒。赶紧把久未见阳光的衣物搬出来吸收一下太阳的味道吧! 
  20.         旅游指数:多云,同时有微风相伴,但温度较高,天气热,请尽量避免高温时段外出,若外出请注意防暑降温和防晒。 
  21.         路况指数:天气较好,路面比较干燥,路况较好,不过天气有点热,定期让车辆休息。 
  22.         舒适度指数:天气炎热,且空气湿度较大,会使您感到很闷热,很不舒适。 
  23.         空气污染指数:气象条件较不利于空气污染物稀释、扩散和清除,请适当减少室外活动时间。 
  24.         紫外线指数:属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。</string> 
  25.     <string>26℃/34℃</string> 
  26.     <string>7月12日 阴转小雨</string> 
  27.     <string>无持续风向微风</string> 
  28.     <string>2.gif</string> 
  29.     <string>7.gif</string> 
  30.     <string>25℃/30℃</string> 
  31.     <string>7月13日 大雨转小雨</string> 
  32.     <string>无持续风向微风</string> 
  33.     <string>9.gif</string> 
  34.     <string>7.gif</string> 
  35.     <string>武汉市位于江汉平原东部,长江中游与长江、汉水交汇处。东经113°41′-115°05′,北纬29°58′-31°22′。武汉市地理位置优越,长江及其最大支流汉江交汇于此,将武汉市区天然分成汉口、汉阳和武昌三镇,武汉是我国水陆交通枢纽,控长江中游之咽喉,扼南北交通之要冲,素有“九省通衢”之称,现全市货运吞吐量达亿吨以上。优越的地理位置,成为历代兵家争夺的战略要地。三国时,武汉东湖附近曾是刘备、孙权、曹操进行军事、政治活动的场所,现在留下的有刘备郊天台、吴王庙、曹操庙、洪山宝塔等古建筑。武汉现已发展为中国中部地区工业、金融、商业、科学、文化教育中心。武汉市属亚热带湿润季风气候,雨量充沛、日照充足,四季分明。总体气候环境良好,近几年30年来,年均降雨量1269毫米,且多集中在6-8月。年均气温15.8℃-17.5℃,年无霜期一般为211天-272天,年日照总时数1810小时-2100小时。景观:武当山、长江三峡、神农架等。</string> 
  36. </ArrayOfString> 

由于这里我只需要显示今天的天气,所以对string提取了7和8那两段进行处理。

测试:执行main方法,结果如下:

今天是星期三 2012年07月11日 天气 多云 ,29度-35度

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值