基于Java的webservice创建与soap方式调用

一、创建(服务端)

建立普通类,代码:

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class TestwebService {
		@WebMethod(operationName="sayHello")
		public String sayHello(String ss){
			return "Hello world!    hello  "+ss;
		}
		
		@WebMethod(operationName="getSum")
		public int getSum(int a,int b){
			return a+b;
		}
		
		
	public static void main(String [] args){
		Endpoint.publish("http://localhost:8083/HelloWorld", new TestwebService());
		System.out.println("发布成功!");
	}
	

}


浏览器键入http://localhost:8083/HelloWorld



二、调用(客户端)

1、利用SoapUI获取请求报文

创建SOAP Project


填写wsdl地址后点击OK


查看soap报文


2、建立webservice请求类:

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.*;
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("return");
			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://localhost:8083/HelloWorld.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",
					"");
			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://
	 * 
	 * 本文采用:SOAP 1.1格式
	 */
	private String getSoapRequest(String city) {
		StringBuffer sb = new StringBuffer();
		sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sys=\"http://sys.controller.jeefw.com/\">");
		sb.append("   <soapenv:Header/>");
		sb.append("   <soapenv:Body>");
		sb.append("      <sys:sayHello>");
		sb.append("         <!--Optional:-->");
		sb.append("         <arg0>"+city+"</arg0>");
		sb.append("      </sys:sayHello>");
		sb.append("   </soapenv:Body>");
		sb.append("</soapenv:Envelope>");


		return sb.toString();
	}
}


3、建立测试类:

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; i++) {
			System.out.println(len[i]);
		}
	}
}


4、测试结果:


调用成功!


  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值