資源簡介
用java代碼調用weather的webservice,實現天氣預報功能
代碼片段和文件信息
package?com.sun.yan;
import?java.io.InputStream;
import?java.io.OutputStream;
import?java.io.OutputStreamWriter;
import?java.net.URL;
import?java.net.URLConnection;
import?javax.xml.parsers.DocumentBuilder;
import?javax.xml.parsers.DocumentBuilderFactory;
import?org.w3c.dom.Document;
import?org.w3c.dom.Node;
import?org.w3c.dom.NodeList;
/**
?*?Java?通過調用外部WebService實現天氣預報的功能
?*?@author?meditator
?*?@create?time?Mar?13?2010
?*?@typename?WeatherReport
?*/
public?class?WeatherReport?{
/**?
?*?獲取SOAP的請求頭,并替換其中的標志符號為用戶輸入的城市?
?*?
?*?@param?city?
?*????????????用戶輸入的城市名稱?
?*?@return?客戶將要發送給服務器的SOAP請求?
?*/
private?static?String?getSoapRequest(String?city)?{
StringBuilder?sb?=?new?StringBuilder();
sb
.append(“l?version=\“1.0\“?encoding=\“utf-8\“?>“
+?“lns:xsi=\“http://www.w3.org/2001/xmlSchema-instance\“?“
+?“xmlns:xsd=\“http://www.w3.org/2001/xmlSchema\“?“
+?“xmlns:soap=\“http://schemas.xmlsoap.org/soap/envelope/\“>“
+?“????lns=\“http://Webxml.com.cn/\“>“
+?““?+?city
+?“ ???? “
+?“ “);
return?sb.toString();
}
/**?
?*?用戶把SOAP請求發送給服務器端,并返回服務器點返回的輸入流?
?*?
?*?@param?city?
?*????????????用戶輸入的城市名稱?
?*?@return?服務器端返回的輸入流,供客戶端讀取?
?*?@throws?Exception?
?*/
private?static?InputStream?getSoapInputStream(String?city)?throws?Exception?{
try?{
String?soap?=?getSoapRequest(city);
if?(soap?==?null)?{
return?null;
}
URL?url?=?new?URL(
“http://www.webxml.com.cn/WebServices/WeatherWebService.asmx“);
URLConnection?conn?=?url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty(“Content-Length“?Integer.toString(soap
.length()));
conn.setRequestProperty(“Content-Type“?“text/xml;?charset=utf-8“);
conn.setRequestProperty(“SOAPAction“
“http://Webxml.com.cn/getWeatherbyCityName“);
OutputStream?os?=?conn.getOutputStream();
OutputStreamWriter?osw?=?new?OutputStreamWriter(os?“utf-8“);
osw.write(soap);
osw.flush();
osw.close();
InputStream?is?=?conn.getInputStream();
return?is;
}?catch?(Exception?e)?{
e.print
評論
共有 條評論