SOAP消息的创建、传递和处理(MESSAGE方式)

本文介绍了一个使用Java实现的SOAP消息交互实例,详细展示了如何创建服务、构建SOAP消息、提交请求并解析响应的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private String ns = "http://service.soap.org/";
private String wsdlUrl = "http://localhost:8989/ms?wsdl";

/**
 * 消息的传递和处理(MESSAGE)
 * 提交给服务器
 */
@Test
public void test02() {
	try {
		//1.创建服务(Service)
		URL url = new URL(wsdlUrl);
		QName sName = new QName(ns, "MyServiceImplService");
		Service service = Service.create(url, sName);
		
		//2.创建Dispatch
		Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns, "MyServiceImplPort"),
				SOAPMessage.class, Service.Mode.MESSAGE);
		
		//3.创建SOAP消息
		//根据消息工厂创建SOAPMessage
		SOAPMessage message = MessageFactory.newInstance().createMessage();
		//通过SOAPPart获取SOAPEnvelope
		SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
		//通过SOAPEnvelope有效获取相应的Body和Header等信息
		SOAPBody body = envelope.getBody();
		
		//4.创建QName来指定消息中传递的数据
		//(QName就是一个带有命名空间的节点)
		QName eName = new QName(ns, "add", "nn");	//<nn:add xmlns="ns" />
		SOAPBodyElement element = body.addBodyElement(eName);
		element.addChildElement("a").setValue("22");
		element.addChildElement("b").setValue("33");
		message.writeTo(System.out);
		System.out.println("\n invoking......");
		
		/*
		 *上面步骤3、4即为SOAP消息体的创建,打印结果为: 
		 * <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
		 * 	<SOAP-ENV:Header/>
		 * 	<SOAP-ENV:Body>
		 * 		<nn:add xmlns:nn="http://service.soap.org/">
		 * 			<a>22</a>
		 * 			<b>33</b>
		 * 		</nn:add>
		 * 	</SOAP-ENV:Body>
		 * </SOAP-ENV:Envelope>
		 * invoking......
		 */

		//5.通过Dispatch传递信息,会返回响应消息
		SOAPMessage response = dispatch.invoke(message);
		response.writeTo(System.out);
		System.out.println();
		/*
		 * 上面步骤为向服务器端传递消息,打印结果为:
		 * <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		 * 	<S:Header/>
		 * 	<S:Body>
		 * 		<ns2:addResponse xmlns:ns2="http://service.soap.org/">
		 * 			<addResult>55</addResult>
		 * 		</ns2:addResponse>
		 * 	</S:Body>
		 * </S:Envelope>
		 */
		
		//6.将响应的消息转换为dom对象(解析xml)
		Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
		String strResult = doc.getElementsByTagName("addResult").item(0).getTextContent();
		System.out.println(strResult);
		/*
		 * 上面步骤为处理消息,即解析返回的SOAP消息
		 * 打印结果为:55
		 */
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (SOAPException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值