资源简介
用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
评论
共有 条评论