The simplest way is to apply for a yahoo dev key, and then you can query the WOEID of the corresponding location through the GeoPlanet api.
The old p parameter is used to pass the location code, but only w parameter is described in the latest api documentation, so WOEID is used here.
If you don't want to register an application key, please do it yourself.
Download the latest GeoPlanet Data and extract the following files:
Geoplanet_places _ [version]. tsv: the WOEID, the placename, and the WOEID of its parent entity
Geoplanet_aliases _ [version]. tsv: alternate names in multiple extensions ages indexed against the WOEID
Geoplanet_adjacencies _ [version]. tsv: the entities neighboring each WOEID
Geoplanet_changes _ [version]. tsv: the list of removed WOEIDs and their replacement WOEID mappings
Here I only use geoplanet_places_7.6.0.tsv, open it with EmEditor, and COPY the data from China to another file Chinaplaces. tsv.
This tsv file uses tab to separate fields. The places file has the following fields:
WOE_ID ISO Name Language PlaceType Parent_ID
Public static HashMap <String, String> cityCode = new HashMap <String, String> ();
/* Initialize the city code */
Private void initCitys (){
CityCode. put ("Beijing'," 0008 ");
CityCode. put ("", "0133 ");
CityCode. put ("Wuhan", "0138 ");
CityCode. put ("Hangzhou", "0044 ");
CityCode. put ("Hefei", "0448 ");
CityCode. put ("Shanghai", "0116 ");
CityCode. put ("Fuzhou", "0031 ");
CityCode. put ("Chongqing", "0017 ");
Citycodes. put ("Nanchang", "0097 ");
CityCode. put ("", "0049 ");
CityCode. put ("ji 'Nan", "0064 ");
CityCode. put ("Macao", "0512 ");
CityCode. put ("Zhengzhou", "0165 ");
CityCode. put ("HOHHOT", "0249 ");
CityCode. put ("Urumqi", "0135 ");
CityCode. put ("", "0013 ");
CityCode. put ("Yinchuan", "0259 ");
CityCode. put ("", "0037 ");
CityCode. put ("Lhasa", "0080 ");
CityCode. put ("", "0502 ");
CityCode. put ("cn", "0100 ");
CityCode. put ("Chengdu", "0016 ");
CityCode. put ("Shijiazhuang", "0122 ");
CityCode. put ("", "0039 ");
CityCode. put ("Taiyuan", "0129 ");
CityCode. put ("Kunming", "0076 ");
CityCode. put ("Shenyang", "0119 ");
CityCode. put ("Xi'an", "0141 ");
CityCode. put ("Changchun", "0010 ");
CityCode. put ("Lanzhou", "0079 ");
CityCode. put ("Xining", "0236 ");
}
Next, we will create a link to obtain the XML document of the weather forecast.
Private Document getWeatherXML (String cityCode) throws IOException {
URL url = new URL ("http://weather.yahooapis.com/forecastrss? P = CHXX"
+ CityCode + "& u = c ");
URLConnection connection = url. openConnection ();
Document Doc = stringToElement (connection. getInputStream ());
Return Doc;
}You can also save the obtained weather XML document.
/* Save the obtained weather information XML document */
Private void saveXML (Document Doc, String Path ){
TransformerFactory transFactory = TransformerFactory. newInstance ();
Transformer transformer;
Try {
Transformer = transFactory. newTransformer ();
DOMSource domSource = new DOMSource (Doc );
File file = new File (Path );
FileOutputStream out = new FileOutputStream (file );
StreamResult xmlResult = new StreamResult (out );
Transformer. transform (domSource, xmlResult );
} Catch (Exception e ){
System. out. println ("An error occurred while saving the file! ");
}
}
Save the XML file obtained by myself as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
-<Rss xmlns: geo = "http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns: yweather = "http://xml.weather.yahoo.com/ns/rss/1.0" version = "2.0">
-<Channel>
<Title> Yahoo! Weather-Wuhan, CH </title>
<Link> Links </link>
<Description> Yahoo! Weather for Wuhan, CH </description>
<Language> en-us </language>
<LastBuildDate> Sat, 27 Mar 2010 pm CST </lastBuildDate>
<Ttl> 60 </ttl>
<Yweather: location city = "Wuhan" country = "CH" region = ""/>
<Yweather: units distance = "km" pressure = "mb" speed = "km/h" temperature = "C"/>
<Yweather: wind chill = "15" direction = "110" speed = "6.44"/>
<Yweather: atmosphere humidity = "67" pressure = "1015.92" rising = "0" visibility = "9.99"/>
<Yweather: astpolicmy sunrise = "19 19 am" sunset = "38 38 pm"/>
-<Image>
<Title> Yahoo! Weather </title>
<Width> 142 </width>
<Height> 18
<Link> http://weather.yahoo.com </link>
<Url> yun_qi_img/main_142b.gif </url>
</Image>
-<Item>
<Title> Conditions for Wuhan, CH at 11: 00 pm CST </title>
<Geo: lat> 30.58 </geo: lat>
<Geo: long> 114.27 </geo: long>
<Link> Links </link>
<PubDate> Sat, 27 Mar 2010 pm CST </pubDate>
<Yweather: condition code = "33" date = "Sat, 27 Mar 2010 pm CST" temp = "15" text = "Fair"/>
-<Description>
-<! -- [CDATA [
<br/>
<B> Current Conditions: </B> <br/>
Fair, 15 C <BR/>
<BR/> <B> Forecast: </B> <BR/>
Sat-Partly Cloudy. High: 18 Low: 9 <br/>
Sun-Partly Cloudy. High: 20 Low: 12 <br/>
<Br/>
<A href = "courier" mce_href = "courier"> Full Forecast at Yahoo! Weather </a> <BR/>
(Provided by <a href = "http://www.weather.com" mce_href = "http://www.weather.com"> The Weather Channel </a>) <br/>
] -->
</Description>
<Yweather: forecast code = "29" date = "27 Mar 2010" day = "Sat" high = "18" low = "9" text = "Partly Cloudy"/>
<Yweather: forecast code = "30" date = "28 Mar 2010" day = "Sun" high = "20" low = "12" text = "Partly Cloudy"/>
<Guid isPermaLink = "false"> CHXX0138_2010_03_27_23_00_CST </guid>
</Item>
</Channel>
</Rss>
-<! -- Api7.weather.sp1.yahoo.com uncompressed/chunked Sat Mar 27 08:43:16 PDT 2010
-->
Well, the following is the parsing of XML. You can take a look at the XML document. If you know it, it is easy to get the information.
/* Obtain weather information */
Public String getWeather (String city ){
String result = null;
Try {
Document doc = getWeatherXML (GetWeatherInfo. cityCode. get (city ));
NodeList nodeList = doc. getElementsByTagName ("channel ");
For (int I = 0; I <nodeList. getLength (); I ++ ){
Node node = nodeList. item (I );
NodeList nodeList1 = node. getChildNodes ();
For (int j = 0; j <nodeList1.getLength (); j ++ ){
Node node1 = nodeList1.item (j );
If (node1.getNodeName (). Inclusignorecase ("item ")){
NodeList nodeList2 = node1.getChildNodes ();
For (int k = 0; k <nodeList2.getLength (); k ++ ){
Node node2 = nodeList2.item (k );
If (node2.getNodeName (). Inclusignorecase (
"Yweather: forecast ")){
NamedNodeMap nodeMap = node2.getAttributes ();
Node lowNode = nodeMap. getNamedItem ("low ");
Node highNode = nodeMap. getNamedItem ("high ");
Node codeNode = nodeMap. getNamedItem ("code ");
String day = "today ";
If (result = null ){
Result = "";
} Else {
Day = "n tomorrow ";
}
Result = result
+ Day
+ ""
+ DictionaryStrings [Integer
. ParseInt (codeNode
. GetNodeValue ()]
+ "T minimum temperature:" + lowNode. getNodeValue ()
+ "℃ T maximum temperature:" + highNode. getNodeValue ()
+ "℃ ";
}
}
}
}
}
SaveXML (doc, "C: UsersyguiDesktopWeather. xml ");
} Catch (Exception e ){
E. printStackTrace ();
}
Return result;
}
The code of the entire program is as follows:
Package stwolf. hustbaidu. java. learn. filelist;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. URL;
Import java.net. URLConnection;
Import java. util. HashMap;
Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;
Import javax. xml. transform. Transformer;
Import javax. xml. transform. TransformerFactory;
Import javax. xml. transform. dom. DOMSource;
Import javax. xml. transform. stream. StreamResult;
Import org. w3c. dom. Document;
Import org. w3c. dom. NamedNodeMap;
Import org. w3c. dom. Node;
Import org. w3c. dom. NodeList;
Class GetWeatherInfo {
Public static HashMap <String, String> cityCode = new HashMap <String, String> ();
Private final String [] dictionaryStrings = {"tornado", "Tropical Storm", "Hurricane", "strong thundershower ",
"Thundershower", "light rain and snow", "rain and hail", "Snow and hail", "Ice Rain", "Mao Yu", "freezing rain", "shower ", "Shower", "light snow ",
"Sporadic light snow", "high snow", "snow", "hail", "sleep", "Dust", "fog", "mist", "smoke ", "Strong Winds", "Windy ",
"Cold", "Cloudy", "Cloudy at night", "Cloudy at Day", "Cloudy at night", "Cloudy at Day", "bright at night", "clear ", "Sunny ",
"Turn fine", "Rain clip hail", "hot", "thundershower", "heavy snow", "snow shower ", "Heavy snow ",
"Cloudy", "Thunder", "snow shower", "thunderstorm "};
Public GetWeatherInfo (){
InitCitys ();
}
/* Initialize the city code */
Private void initCitys (){
CityCode. put ("Beijing'," 0008 ");
CityCode. put ("", "0133 ");
CityCode. put ("Wuhan", "0138 ");
CityCode. put ("Hangzhou", "0044 ");
CityCode. put ("Hefei", "0448 ");
CityCode. put ("Shanghai", "0116 ");
CityCode. put ("Fuzhou", "0031 ");
CityCode. put ("Chongqing", "0017 ");
Citycodes. put ("Nanchang", "0097 ");
CityCode. put ("", "0049 ");
CityCode. put ("ji 'Nan", "0064 ");
CityCode. put ("Macao", "0512 ");
CityCode. put ("Zhengzhou", "0165 ");
CityCode. put ("HOHHOT", "0249 ");
CityCode. put ("Urumqi", "0135 ");
CityCode. put ("", "0013 ");
CityCode. put ("Yinchuan", "0259 ");
CityCode. put ("", "0037 ");
CityCode. put ("Lhasa", "0080 ");
CityCode. put ("", "0502 ");
CityCode. put ("cn", "0100 ");
CityCode. put ("Chengdu", "0016 ");
CityCode. put ("Shijiazhuang", "0122 ");
CityCode. put ("", "0039 ");
CityCode. put ("Taiyuan", "0129 ");
CityCode. put ("Kunming", "0076 ");
CityCode. put ("Shenyang", "0119 ");
CityCode. put ("Xi'an", "0141 ");
CityCode. put ("Changchun", "0010 ");
CityCode. put ("Lanzhou", "0079 ");
CityCode. put ("Xining", "0236 ");
}
Private Document getWeatherXML (String cityCode) throws IOException {
URL url = new URL ("http://weather.yahooapis.com/forecastrss? P = CHXX"
+ CityCode + "& u = c ");
URLConnection connection = url. openConnection ();
Document Doc = stringToElement (connection. getInputStream ());
Return Doc;
}
/* Save the obtained weather information XML document */
Private void saveXML (Document Doc, String Path ){
TransformerFactory transFactory = TransformerFactory. newInstance ();
Transformer transformer;
Try {
Transformer = transFactory. newTransformer ();
DOMSource domSource = new DOMSource (Doc );
File file = new File (Path );
FileOutputStream out = new FileOutputStream (file );
StreamResult xmlResult = new StreamResult (out );
Transformer. transform (domSource, xmlResult );
} Catch (Exception e ){
System. out. println ("An error occurred while saving the file! ");
}
}
/* Obtain weather information */
Public String getWeather (String city ){
String result = null;
Try {
Document doc = getWeatherXML (GetWeatherInfo. cityCode. get (city ));
NodeList nodeList = doc. getElementsByTagName ("channel ");
For (int I = 0; I <nodeList. getLength (); I ++ ){
Node node = nodeList. item (I );
NodeList nodeList1 = node. getChildNodes ();
For (int j = 0; j <nodeList1.getLength (); j ++ ){
Node node1 = nodeList1.item (j );
If (node1.getNodeName (). Inclusignorecase ("item ")){
NodeList nodeList2 = node1.getChildNodes ();
For (int k = 0; k <nodeList2.getLength (); k ++ ){
Node node2 = nodeList2.item (k );
If (node2.getNodeName (). Inclusignorecase (
"Yweather: forecast ")){
NamedNodeMap nodeMap = node2.getAttributes ();
Node lowNode = nodeMap. getNamedItem ("low ");
Node highNode = nodeMap. getNamedItem ("high ");
Node codeNode = nodeMap. getNamedItem ("code ");
String day = "today ";
If (result = null ){
Result = "";
} Else {
Day = "n tomorrow ";
}
Result = result
+ Day
+ ""
+ DictionaryStrings [Integer
. ParseInt (codeNode
. GetNodeValue ()]
+ "T minimum temperature:" + lowNode. getNodeValue ()
+ "℃ T maximum temperature:" + highNode. getNodeValue ()
+ "℃ ";
}
}
}
}
}
SaveXML (doc, "C: UsersyguiDesktopWeather. xml ");
} Catch (Exception e ){
E. printStackTrace ();
}
Return result;
}
Public Document stringToElement (InputStream input ){
Try {
DocumentBuilder db = DocumentBuilderFactory. newInstance ()
. NewDocumentBuilder ();
Document doc = db. parse (input );
Return doc;
} Catch (Exception e ){
Return null;
}
}
}
Public class Test {
Public static void main (String arg []) {
GetWeatherInfo info = new GetWeatherInfo ();
String weather = info. getWeather ("Wuhan ");
System. out. println (weather );
}
}