您的位置:首页 > 其它

WebServicel通过城市名查询天气

2017-12-14 15:19 127 查看
网站: WebXml

通过城市名称查天气

接口类:

public interface WeatherService {

void getWeatherByCity(String cityName);

}


实现接口类:

public class WeatherServiceImpl implements WeatherService {

/**
* 以字符串的形式,准备请求头
*
* @param cityname 城市名
* @return
*/
public String getRequestheaderToString(String cityname) {
String reqStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
"  <soap12:Body>" +
"    <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">" +
"      <theCityName>" + cityname + "</theCityName>" +
"    </getWeatherbyCityName>" +
"  </soap12:Body>" +
"</soap12:Envelope>";
return reqStr;
}

/**
* 通过HttpURLConnection来发送请求,并返回结果
*
* @param requestString 请求头的文本信息
* @return 以流的形式返回查询结果(xml文档)
*/
public InputStream sendRequestSoap(String requestString) {
try {
URL url = new URL("http://ws.webxml.com.cn/WebServices/WeatherWebService.asmx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Host", "ws.webxml.com.cn");
conn.setRequestProperty("Content-Type", "application/soap+xml;charset=utf-8");
conn.setRequestProperty("Content-Length", requestString.length() + "");

OutputStream os = conn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "utf-8");
writer.write(requestString);
writer.flush();
writer.close();
return conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

public void getWeatherByCity(String cityName) {
InputStream is = this.sendRequestSoap(this.getRequestheade
4000
rToString(cityName));

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);

NodeList list = doc.getElementsByTagName("string");
if (!list.item(0).getFirstChild().getNodeValue().equals("查询结果为空")) {
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
System.out.println(node.getFirstChild().getNodeValue());
}
} else {
System.out.println("查询结果为空!");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
WeatherServiceImpl service = new WeatherServiceImpl();
service.getWeatherByCity("深圳");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webservice