javaEE中使用webservice

Java EE整合Web Service实现天气查询
本文介绍了在Java EE项目中如何利用Web Service获取并展示天气信息,具体以调用免费的WeatherWebService为例,提供了WeatherUtil.java工具类的代码示例,并提及了XML解析方法。

有时会看到某一个网站上面会有天气预报,这些天气预报有的是直接调用了免费的webservice。


一些免费的webservice:http://www.webxml.com.cn/zh_cn/web_services.aspx

这里测试使用天气接口:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx


代码:WeatherUtil.java工具类:

package com.mfc.test;

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;

/**
 * 2017-8-27 16:33:04
 * 获取天气预报的工具类
 * */
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);
			
			/*
			 * 这些信息查看http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName里面的:
			 *  POST /WebServices/WeatherWebService.asmx HTTP/1.1
				Host: www.webxml.com.cn
				Content-Type: text/xml; charset=utf-8
				Content-Length: length
				SOAPAction: "http://WebXml.com.cn/getWeatherbyCityName"
			 * */
			
			
			conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			
			/*
			 * 这里的1和2对应着getSoapRequest里面的1和2
			 * */
			// 调用的接口方法是“getWeatherbyCityName”
			//2、获取对应城市的天气预报
			conn.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName");
			//1、获取对应省份的所有城市
			//conn.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getSupportCity ");
			
			
			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();
		
		/*
		 * 以下信息查看http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName里面的:
		 * <?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>string</theCityName>
			    </getWeatherbyCityName>
			  </soap:Body>
			</soap:Envelope>
		 * */
		
		//2、获取对应城市的天气预报,获取其他信息以此类推
		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>");
		
	
		//1、获取对应省份的所有城市,获取其他信息以此类推
		/*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>"
				+ "<getSupportCity xmlns=\"http://WebXml.com.cn/\">"
				+ "<byProvinceName>"+city+"</byProvinceName>"
				+ "</getSupportCity>"
				+ "</soap:Body>"
				+ "</soap:Envelope>");*/
		 
		return sb.toString();
	}
}

这里说一下一些代码汇总信息的获取:

例如在:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName中:

这里使用DOM解析XML,更多解析XML的方法:http://blog.youkuaiyun.com/fancheng614/article/details/77131034


测试代码:

package com.mfc.test;

public class LogonClientWithURL {

	/**
	 * 测试
	 */
	public static void main(String[] args) throws Exception {
		WeatherUtil weath = new WeatherUtil();

		// 查看城市:襄阳
		//注意:这个webservice里面还没有将襄樊改名为襄阳
		//如果要查看对应省份下所有的城市,这里的“襄樊”就应该换成某个省份的名称,如“湖北”
		String weather = weath.getWeather("襄樊");
		String len[] = weather.split("#");
		for (int i = 0; i < len.length - 1; i++) {
			System.out.println(len[i]);
		}
	}
}

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值