Weather forecast is a very useful service. If you can integrate the weather forecast on your website, you can query it easily.
I searched all the meteorological sites in China and did not find any web service. I was too stingy to go abroad. NOAA (Www.weather.gov) Provides a Web service, but cannot connect to the server. It is estimated that it is blocked.Www.weather.comAnd Yahoo,
However, weather.com is too troublesome and requires registration. In contrast, Yahoo's weather service is simple and fast. You only need an HTTP request and parse the returned XML to obtain the weather forecast.
Take Beijing as an example. In weather.yahoo.com, the city code of Beijing is chxx0008, and the corresponding URL is:
Http://xml.weather.yahoo.com/forecastrss? U = C & P = chxx0008
Then, parse the returned XML using sax:
URL url = new URL ("Http://xml.weather.yahoo.com/forecastrss? U = C & P = chxx0008");
Inputstream input = URL. openstream ();
Saxparserfactory factory = saxparserfactory. newinstance ();
Factory. setnamespaceaware (false );
Saxparser parser = factory. newsaxparser ();
Parser. parse (input, new yahoohandler ());
Define a custom yahoohandler to respond to the sax event:
/**
* For more information, please visit:Http://www.crackj2ee.com
* Author: Liao Xuefeng
*/
Public class yahoohandler extends defaulthandler {
Public void startelement (string Uri, string localname, string QNAME, attributes)
Throws saxexception {
If ("yweather: condition". Equals (QNAME )){
String s_date = attributes. getvalue (3 );
Try {
Date publish = new simpledateformat ("Eee, DD Mmm yyyy hh: mm a Z ",
Locale. Us). parse (s_date );
// System. Out. println ("publish:" + publish. tostring ());
}
Catch (exception e ){
E. printstacktrace ();
Throw new saxexception ("cannot parse Date:" + s_date );
}
}
Else if ("yweather: Forecast". Equals (QNAME )){
String s_date = attributes. getvalue (1 );
Date = NULL;
Try {
Date = new simpledateformat ("DD Mmm YYYY", locale. Us). parse (s_date );
}
Catch (exception e ){
E. printstacktrace ();
Throw new saxexception ("cannot parse Date:" + s_date );
}
Int low = integer. parseint (attributes. getvalue (2 ));
Int high = integer. parseint (attributes. getvalue (3 ));
String text = attributes. getvalue (4 );
Int code = integer. parseint (attributes. getvalue (5 ));
System. Out. println ("weather:" + TEXT + ", low =" + low + ", high =" + high );
}
Super. startelement (Uri, localname, QNAME, attributes );
}
}
Running result:
WEATHER: partly cloudy, low = 7, high = 16
WEATHER: Sunny, low = 7, high = 20
Yahoo returns the weather forecast for the current day and the next day.