天天看点

[Java基础]-- java调用天气预报webservice

一、说明

天气预报的webService地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

(天气预报 Web 服务,数据每2.5小时左右自动更新一次,准确可靠。包括 340 多个中国主要城市和 60 多个国外主要城市三日内的天气预报数据。此天气预报Web Services请不要用于任何商业目的,若有需要请​​联系我们​​,欢迎技术交流。 QQ:8409035)

二、相关信息调用举例以及说明

1、新建一个java类:WeatherUtil.java

package com.test.util;
 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;
 public class WeatherUtil {
 /**
 * 对服务器端返回的XML文件流进行解析
 * 
 * @param city 用户输入的城市名称
 * @return          字符串 用#分割
 */
 public  String getWeather(String city) {
 try {
 //使用Dom解析
 Document doc;
 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 dbf.setNamespaceAware(true);
 DocumentBuilder db = dbf.newDocumentBuilder();
 //获取调用接口后返回的流
 InputStream is = getSoapInputStream(city);
 doc = db.parse(is);
 //xml的元素标签是"<string>值1</string><string>值2</string>……"
 NodeList nl = doc.getElementsByTagName("string");
 StringBuffer sb = new StringBuffer();
 for (int count = 0; count < nl.getLength(); count++) {
 Node n = nl.item(count);
 if(n.getFirstChild().getNodeValue().equals("查询结果为空!")) {
 sb = new StringBuffer("#") ;
 break ;
 }
 //解析并以"#"为分隔符,拼接返回结果
 sb.append(n.getFirstChild().getNodeValue() + "#");
 }
 is.close();
 return sb.toString();
 } catch (Exception e) {
 e.printStackTrace();
 return null;
 }
 }
 /*
 * 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流
 * 
 * @param city  用户输入的城市名称
 * @return 服务器端返回的输入流,供客户端读取
 * @throws Exception
 * @备注:有四种请求头格式1、SOAP 1.1;  2、SOAP 1.2 ; 3、HTTP GET; 4、HTTP POST
 * 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
 */
 private  InputStream getSoapInputStream(String city) throws Exception {
 try {
//获取请求规范
 String soap = getSoapRequest(city);
 if (soap == null) {
 return null;
 }
 //调用的天气预报webserviceURL
 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");
 //调用的接口方法是“getWeatherbyCityName”
 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();
 //获取webserivce返回的流
 InputStream is = conn.getInputStream();
 return is;
 } catch (Exception e) {
 e.printStackTrace();
 return null;
 }
 }
 /*
 * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市
 * 
 * @param city: 用户输入的城市名称
 * @return              客户将要发送给服务器的SOAP请求规范
 * @备注:有四种请求头格式1、SOAP 1.1;  2、SOAP 1.2 ; 3、HTTP GET; 4、HTTP POST
 * 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
 * 本文采用:SOAP 1.1格式
 */
 private  String getSoapRequest(String city) {
 StringBuilder sb = new StringBuilder();
 sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
 + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
 + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
 + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
 + "<soap:Body><getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
 + "<theCityName>" 
 + city
 + "</theCityName></getWeatherbyCityName>"
 + "</soap:Body></soap:Envelope>");
 return sb.toString();
 }
 }      

注:webservice返回的xml文件如下

[Java基础]-- java调用天气预报webservice

2、新建一个测试类:TestWeather.java

package com.util;
 import com.test.util.WeatherUtil;
 public class TestWeather {
 /**
 * 测试
 */
 public static void main(String[] args) throws Exception {
 WeatherUtil weath=new WeatherUtil();//查看城市:济南
 String weather=weath.getWeather("济南");
 String len[]=weather.split("#");
 for(int i=0;i<len.length-1;i++){
 System.out.println(len[i]);
 }
 /**
 * 打印结果:
 * 山东
 * 济南
 * 54823
 * 54823.jpg
   * 2016-3-5 13:52:01
 * 4℃/14℃
 * 3月5日 多云转晴
 * 北风3-4级转南风微风
 * 1.gif
 * 0.gif
 * 今日天气实况:气温:12℃;风向/风力:东北风 2级;湿度:23%;紫外线强度:弱。空气质量:良。
 * 紫外线指数:弱,辐射较弱,涂擦SPF12-15、PA+护肤品。
       感冒指数:极易发,强降温,湿度较大,极易感冒。
       穿衣指数:较冷,建议着厚外套加毛衣等服装。
       洗车指数:较适宜,无雨且风力较小,易保持清洁度。
       交通指数:良好,气象条件良好,车辆可以正常行驶。
 空气污染指数:良,气象条件有利于空气污染物扩散。
   * 7℃/17℃
 * 3月6日 多云
 * 南风微风
 * 1.gif
 * 1.gif
 * 4℃/16℃
 * 3月7日 多云
 * 南风微风转北风3-4级
 * 1.gif
 * 1.gif
 */}
 }