java 获得天气预报信息
java 獲得天氣預(yù)報(bào)信息
最近項(xiàng)目中需要增加天氣預(yù)報(bào)功能,網(wǎng)上給的資料有很多缺陷比如
1.?????? 有些小網(wǎng)站提供的webservers本身就不穩(wěn)定不能長(zhǎng)期使用。
2.?????? 還有一些網(wǎng)站限制訪問次數(shù)。
3.?????? 再有就是花錢買服務(wù)。
?
根據(jù)以上幾點(diǎn)只能放棄使用第三方的webservers,由此我們只能找個(gè)信得過的提供天氣預(yù)報(bào)的網(wǎng)站抓取頁(yè)面信息。
接下來(lái)我們以中央氣象臺(tái)為例實(shí)現(xiàn)從請(qǐng)求到數(shù)據(jù)解析的過程。
?
1.?????? 瀏覽http://www.nmc.gov.cn/ 發(fā)現(xiàn)一個(gè)搜索功能
?
做過網(wǎng)頁(yè)的人都知道通過表單提交城市名字,那我們?nèi)タ纯淳唧w提交到什么地方呢。
?
在這個(gè)from表單中我們發(fā)現(xiàn)了什么?對(duì)有action 和 keys 這都知道是什么意思我就不廢話了。
最終我們得到一個(gè)url : http://www.nmc.gov.cn/search_result.php?keys=城市名字
哈哈,這就是我們獲得天氣預(yù)報(bào)的關(guān)鍵。
?
2.?????? 通過程序訪問url.
以下是使用HttpClient的例子
HttpClient client = new HttpClient();//實(shí)例
String url="http://www.nmc.gov.cn//search_result.php?keys="+city;
method =? new GetMethod(url);//通過Get方式訪問
httpstatus = client.executeMethod(method);
if(httpstatus==200)//200表示成功
{
//獲得響應(yīng)轉(zhuǎn)碼為GBK,否則中文會(huì)亂碼
String? result=newString
(method.getResponseBodyAsString().getBytes("iso-8859-1"),"GBK");
}
?
用上面的程序訪問你會(huì)發(fā)現(xiàn)報(bào)錯(cuò)了 Invalid query? ;這里我們需要將城市名字轉(zhuǎn)碼
?
String url="http://www.nmc.gov.cn//search_result.php?
keys="+URLEncoder.encode(city,”GBK”);
?
這樣在url中中文就是轉(zhuǎn)碼后的不會(huì)出現(xiàn)亂碼。
?
3.?????? 解析數(shù)據(jù)
以北京為例提交后網(wǎng)頁(yè)信息為:
?
?
對(duì)應(yīng)的頁(yè)面中的代碼為:
?
至此我們就可以獲得天氣信息了。。。。解析的代碼如下:
?
??????? public? void ParaseHtml(String html)
??? {
?
?????? String climate = ParaseWeatherInfo(html,"天氣");
?????? String temperature = ParaseWeatherInfo(html,"氣溫");
?????? String wind = ParaseWeatherInfo(html,"風(fēng)");
?????? String barometric = ParaseWeatherInfo(html,"氣壓");
??????
?????? log.debug("天氣:"+climate +"/ 氣溫 :"+temperature +"/ 風(fēng) "+wind +"/ 氣壓"+barometric);
??? }
??? public? String ParaseWeatherInfo(String str,String word)
??? {
?????? String w = null;
?????? String st = "w365line1";
?????? //System.err.println(str);
?????? int a = str.indexOf(st);
?????? if(a!= -1)
?????? {
?????????? String div1 = "<div";
?????????? String div2 = "</div>";
?????????? String keyword = ":";
?????????? int d1 = str.lastIndexOf(div1, a);
?????????? int d2 = str.indexOf(div2, a);
?????????? if(d2 != -1)
?????????? {
????????????? String str4 = null;
????????????? String str2 = str.substring(d1, d2+div2.length());
????????????? if(str2.indexOf(word) !=-1)
????????????? {
????????????????? str4 = filerStr(str2,word,"");
????????????????? int k1 = str4.indexOf(keyword);
????????????????? str4 = str4.substring(k1+1,str4.length()).trim();
????????????????? return str4;
????????????? }??
????????????? else
????????????? {
????????????????? String s5 = str.replace(str2, "");
????????????????? w = ParaseWeatherInfo(s5,word);
????????????????? return w;
????????????? }
?????????? }
?????? }
??????
?????? return w;
??? }
??? public? String filerStr(String html,String word,String replacement)
??? {???
??? try{
??????? if(replacement==null)
??????????? replacement = "";
??????? String?? str=html;?
??????????? String?? str1="(<[^>]*>)|( )";?
??????????? Pattern?? p=Pattern.compile(str1);?
??????????? Matcher?? m=p.matcher(str);?
??????????? boolean?? f=m.find();?
??????????? StringBuffer?? sb=new?? StringBuffer();??
??????????? while(f)?? {?
??????????
??????????????? m.appendReplacement(sb,replacement);?
??????????????? f=m.find();?
??????????? }?
??????????? m.appendTail(sb);
???????????
??????????? return sb.toString();
???????
??? }
??? catch(Exception e)
??? {
???????
??? }
???
??? return html;
??? }
?
抓取北京的天氣信息:
?????? String html = WeatherUtil2.getInstance().getNMCRespones("北京");
?????? WeatherUtil2.getInstance().ParaseHtml(html);
?
天氣:多云/ 氣溫 :30 ℃/ 風(fēng) 西南風(fēng),3級(jí),4米/秒/ 氣壓1001.8hPa
?
?
===================
java 獲取天氣預(yù)報(bào)實(shí)現(xiàn)代碼
最簡(jiǎn)單的辦法是申請(qǐng)一個(gè)yahoo dev 的key ,然后就可以通過 GeoPlanet api 來(lái)查詢相應(yīng)地點(diǎn)的WOEID了。用的是舊的p 參數(shù)傳遞地點(diǎn)代碼,不過最新的api文檔里面只對(duì)w參數(shù)作了
說明,因此這里我就用WOEID了。不想注冊(cè)申請(qǐng)key,還是自己折騰吧。下載最新的 GeoPlanet Data ,解壓出來(lái)有這些個(gè)文件:geoplanet_places_[version].tsv: the WOEID, the
placename, and the WOEID of its parent entitygeoplanet_aliases_[version].tsv: alternate names in multiple languages indexed against the
WOEIDgeoplanet_adjacencies_[version].tsv: the entities neighboring each WOEIDgeoplanet_changes_[version].tsv: the list of removed WOEIDs and their
replacement WOEID mappings
?這里我只取 geoplanet_places_7.6.0.tsv ,用EmEditor 打開,把 中國(guó) 地區(qū)的 COPY 出到另外一個(gè)文件Chinaplaces.tsv .
這個(gè)tsv 文件是用tab分隔字段的,places文件的字段有:WOE_ID ISO Name Language PlaceType Parent_ID
?
public static HashMap<String, String> cityCode = new HashMap<String, String>();??? /* 初始化城市代號(hào) */private void initCitys() {??? cityCode.put("北京",
"0008");??? cityCode.put("天津", "0133");??? cityCode.put("武漢", "0138");??? cityCode.put("杭州", "0044");??? cityCode.put("合肥 ", "0448");???
cityCode.put("上海 ", "0116");??? cityCode.put("福州 ", "0031");??? cityCode.put("重慶 ", "0017");??? cityCode.put("南昌 ", "0097");??? cityCode.put("香港 ",
"0049");??? cityCode.put("濟(jì)南 ", "0064");??? cityCode.put("澳門 ", "0512");??? cityCode.put("鄭州 ", "0165");??? cityCode.put("呼和浩特 ", "0249");???
cityCode.put("烏魯木齊 ", "0135");??? cityCode.put("長(zhǎng)沙 ", "0013");??? cityCode.put("銀川 ", "0259");??? cityCode.put("廣州 ", "0037");??? cityCode.put("拉
薩 ", "0080");??? cityCode.put("海口 ", "0502");??? cityCode.put("南京 ", "0100");??? cityCode.put("成都 ", "0016");??? cityCode.put("石家莊 ", "0122");???
cityCode.put("貴陽(yáng) ", "0039");??? cityCode.put("太原 ", "0129");??? cityCode.put("昆明 ", "0076");??? cityCode.put("沈陽(yáng) ", "0119");??? cityCode.put("西安 ",
"0141");??? cityCode.put("長(zhǎng)春 ", "0010");??? cityCode.put("蘭州 ", "0079");??? cityCode.put("西寧 ", "0236");}
--------------------------------------------------------------------------------
接下來(lái)我們要?jiǎng)?chuàng)建鏈接,以獲取天氣預(yù)報(bào)的XML文檔
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;??? }
--------------------------------------------------------------------------------
您也可以選擇保存獲取的天氣XML文檔
/* 保存獲取的天氣信息XML文檔 */??? 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("保存文件出錯(cuò)!");??????? }??? }
--------------------------------------------------------------------------------
本人獲取的一份XML保存如下
<?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>http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html</link>?? <description>Yahoo! Weather for
Wuhan, CH</description>?? <language>en-us</language>?? <lastBuildDate>Sat, 27 Mar 2010 11:00 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:astronomy sunrise="6:19
am" sunset="6:38 pm" /> - <image>? <title>Yahoo! Weather</title>?? <width>142</width>?? <height>18</height>?? <link>http://weather.yahoo.com</link>??
<url>http://l.yimg.com/a/i/us/nws/th/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>http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html</link>?? <pubDate>Sat, 27 Mar 2010 11:00 pm
CST</pubDate>?? <yweather:condition code="33" date="Sat, 27 Mar 2010 11:00 pm CST" temp="15" text="Fair" /> - <description>- <!--[CDATA[ <img
src="http://l.yimg.com/a/i/us/we/52/33.gif" mce_src="http://l.yimg.com/a/i/us/we/52/33.gif"/><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="http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html"
mce_href="http://us.rd.yahoo.com/dailynews/rss/weather/Wuhan__CH/*http://weather.yahoo.com/forecast/CHXX0138_c.html">Full Forecast at Yahoo!
Weather</a><BR/><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?? -->
--------------------------------------------------------------------------------
好啦,下面就是解析XML了,您看一下XML文檔,如果您了解的話很容易獲取其中的信息
/* 獲取天氣信息 */??? 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().equalsIgnoreCase("item")) {??????
???????????????? NodeList nodeList2 = node1.getChildNodes();??????????????????????? for (int k = 0; k < nodeList2.getLength(); k++) {????????????????????????
?? Node node2 = nodeList2.item(k);??????????????????????????? if (node2.getNodeName().equalsIgnoreCase(???????????????????????????????????
"yweather:forecast")) {??????????????????????????????? NamedNodeMap nodeMap = node2.getAttributes();??????????????????????????????? Node lowNode =
nodeMap.getNamedItem("low");??????????????????????????????? Node highNode = nodeMap.getNamedItem("high");??????????????????????????????? Node codeNode =
nodeMap.getNamedItem("code");??????????????????????????????? String day = "今天";??????????????????????????????? if (result == null) {???????????????????????
?? (www.111cn.net)???????? result = "";??????????????????????????????? } else {??????????????????????????????????? day = "n明天";????????????????????????????
?? }??????????????????????????????? result = result??????????????????????????????????????? + day??????????????????????????????????????? + " "????????????????
?????????????????????? + dictionaryStrings[Integer??????????????????????????????????????????????? .parseInt(codeNode?????????????????????????????????????????
????????????? .getNodeValue())]??????????????????????????????????????? + "t最低溫度:" + lowNode.getNodeValue()??????????????????????????????????????? + "℃
t最高溫度:" + highNode.getNodeValue()??????????????????????????????????????? + "℃ ";??????????????????????????? }??????????????????????? }?????????????????
? }??????????????? }??????????? }??????????? saveXML(doc, "C:UsersyguiDesktopWeather.xml");??????? } catch (Exception e) {??????????? e.printStackTrace();???
??? }??????? return result;??? }
--------------------------------------------------------------------------------
整個(gè)程序的代碼如下:
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 = { "龍卷風(fēng)", "熱帶風(fēng)暴", "颶風(fēng)", "強(qiáng)雷陣雨",??????????? "雷陣雨", "小雨加雪", "雨加冰雹", "雪加冰雹", "冰雨", "毛毛
雨", "凍雨", "陣雨", "陣雨", "小雪",??????????? "零星小雪", "高吹雪", "雪", "冰雹", "雨夾雪", "塵", "霧", "薄霧", "多煙的", "大風(fēng)", "有風(fēng)",??????????? "寒
冷", "陰天", "夜間陰天", "白天陰天", "夜間多云", "白天多云", "夜間清亮", "晴朗", "轉(zhuǎn)晴",??????????? "轉(zhuǎn)晴", "雨夾冰雹", "熱", "雷陣雨", "雷陣雨", "雷陣雨", "
雷陣雨", "大雪", "陣雪", "大雪",??????????? "多云", "雷", "陣雪", "雷雨" };??? public GetWeatherInfo() {??????? initCitys();??? }??? /* 初始化城市代號(hào) */???
private void initCitys() {??????? cityCode.put("北京", "0008");??????? cityCode.put("天津", "0133");??????? cityCode.put("武漢", "0138");???????
cityCode.put("杭州", "0044");??????? cityCode.put("合肥 ", "0448");??????? cityCode.put("上海 ", "0116");??????? cityCode.put("福州 ", "0031");???????
cityCode.put("重慶 ", "0017");??????? cityCode.put("南昌 ", "0097");??????? cityCode.put("香港 ", "0049");??????? cityCode.put("濟(jì)南 ", "0064");???????
cityCode.put("澳門 ", "0512");??????? cityCode.put("鄭州 ", "0165");??????? cityCode.put("呼和浩特 ", "0249");??????? cityCode.put("烏魯木齊 ", "0135");?????
? cityCode.put("長(zhǎng)沙 ", "0013");??????? cityCode.put("銀川 ", "0259");??????? cityCode.put("廣州 ", "0037");??????? cityCode.put("拉薩 ", "0080");???????
cityCode.put("海口 ", "0502");??????? cityCode.put("南京 ", "0100");??????? cityCode.put("成都 ", "0016");??????? cityCode.put("石家莊 ", "0122");???????
cityCode.put("貴陽(yáng) ", "0039");??????? cityCode.put("太原 ", "0129");??????? cityCode.put("昆明 ", "0076");??????? cityCode.put("沈陽(yáng) ", "0119");???????
cityCode.put("西安 ", "0141");??????? cityCode.put("長(zhǎng)春 ", "0010");??????? cityCode.put("蘭州 ", "0079");??????? cityCode.put("西寧 ", "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;??? }??? /* 保存獲取的天氣信息XML文檔 */??? 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("保存
文件出錯(cuò)!");??????? }??? }??? /* 獲取天氣信息 */??? 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().equalsIgnoreCase
("item")) {??????????????????????? NodeList nodeList2 = node1.getChildNodes();??????????????????????? for (int k = 0; k < nodeList2.getLength(); k++) {??????
???????????????????? Node node2 = nodeList2.item(k);??????????????????????????? if (node2.getNodeName().equalsIgnoreCase(???????????????????????????????????
"yweather:forecast")) {??????????????????????????????? NamedNodeMap nodeMap = node2.getAttributes();??????????????????????????????? Node lowNode =
nodeMap.getNamedItem("low");??????????????????????????????? Node highNode = nodeMap.getNamedItem("high");??????????????????????????????? Node codeNode =
nodeMap.getNamedItem("code");??????????????????????????????? String day = "今天";??????????????????????????????? if (result == null) {???????????????????????
??????????? result = "";??????????????????????????????? } else {??????????????????????????????????? day = "n明天";??????????????????????????????? }??????????
???????????????????? result = result??????????????????????????????????????? + day??????????????????????????????????????? + " "???????????????????????????????
??????? + dictionaryStrings[Integer??????????????????????????????????????????????? .parseInt(codeNode???????????????????????????????????????????????????????
.getNodeValue())]??????????????????????????????????????? + "t最低溫度:" + lowNode.getNodeValue()??????????????????????????????????????? + "℃ t最高溫度:" +
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("武漢");??????? System.out.println(weather);??? }}
from:http://www.111cn.net/jsp/Java/39375.htm
?
?====================
JAVA Webservices 實(shí)現(xiàn)天氣預(yù)報(bào)
?
http://www.webxml.com.cn/Webservices/WeatherWebService.asmx
下面就用java把具體的代碼寫寫吧!
這里我采用比較簡(jiǎn)單的get請(qǐng)求調(diào)用,畢竟這也沒什么秘密可言,就用最簡(jiǎn)單的就可以了。
還有,這里很多捕獲異常的東西給我去掉了,自己加吧!
?
{???
private static String SERVICES_HOST = "www.webxml.com.cn";
private static String WEATHER_SERVICES_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/";
private static String SUPPORT_CITY_URL = WEATHER_SERVICES_URL
+ "getSupportCity?byProvinceName=ALL";
private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL
+ "getWeatherbyCityName?theCityName=";
private WeatherUtil(){}
public static InputStream getSoapInputStream(String url)
{
InputStream is = null;
URL U = new URL(url);
URLConnection conn = U.openConnection();
conn.setRequestProperty("Host", SERVICES_HOST);
conn.connect();
is = conn.getInputStream();
return is;
}
//取得支持的城市列表
public static ArrayList<String> getSupportCity()
{
ArrayList cityList = null;
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(SUPPORT_CITY_URL);
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
int len = nl.getLength();
cityList = new ArrayList<String>(len);
for (int i = 0; i < len; i++)
{
Node n = nl.item(i);
String city = n.getFirstChild().getNodeValue();
cityList.add(city);
}
is.close();
return cityList;
}
//取得城市的天氣
public static ArrayList<String> getWeather(String city)
{
ArrayList weatherList = null;
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
//這里他的編碼格式就是這樣,我試了幾個(gè)也沒辦法。。只好這樣混過去了
InputStream is = getSoapInputStream(WEATHER_QUERY_URL
+ new String(city.getBytes("UTF-8"), "GBK"));
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
int len = nl.getLength();
weatherList = new ArrayList<String>(len);
for (int i = 0; i < len; i++)
{
Node n = nl.item(i);
String weather = n.getFirstChild().getNodeValue();
weatherList.add(weather);
}
is.close();
return weatherList;
}
public static void main(String[] args) throws Exception
{
ArrayList<String> weatherList = WeatherUtil.getWeather("59287");
// ArrayList<String> weatherList = WeatherUtil.getSupportCity();
for (String weather : weatherList)
{
System.out.println(weather);
}
}
}
?
總結(jié)
以上是生活随笔為你收集整理的java 获得天气预报信息的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查看数据库版本
- 下一篇: w3cschool教程之jQuery U