【发布时间】:2011-08-22 13:18:25
【问题描述】:
以下是我应该从我的 Java Web 应用程序调用的 .NET Web 服务的通用示例 SOAP 请求:
<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>
<setAMRequestData xmlns="http://tempuri.org/">
<id>int</id>
</setAMRequestData>
</soap:Body>
</soap:Envelope>
我可以使用这个代码段从 java 控制台应用程序生成类似的东西:
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
...
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage sm = mf.createMessage();
SOAPHeader sh = sm.getSOAPHeader();
SOAPBody sb = sm.getSOAPBody();
sh.detachNode();
QName bodyName = new QName("http://tempuri.org/", "setAMRequestData", XMLConstants.DEFAULT_NS_PREFIX);
SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
QName n = new QName("id");
SOAPElement quotation = bodyElement.addChildElement(n);
quotation.addTextNode("121152");
结果是以下 XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<setAMRequestData xmlns="http://tempuri.org/">
<id>121152</id>
</setAMRequestData>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
这会调用服务。接下来,我使用 soapUI 来尝试调用该服务,它从 WSDL 生成了类似这样的肥皂消息(它与之前在信封中的命名空间声明中不同,以及前缀):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:setAMRequestData>
<tem:id>?</tem:id>
</tem:setAMRequestData>
</soapenv:Body>
</soapenv:Envelope>
这也适用于soapUI。但最后,当我尝试使用此代码序列重新创建这种形式的肥皂消息时:
// factories and stuff, like in the example above
SOAPPart part = sm.getSOAPPart();
SOAPEnvelope envelope = part.getEnvelope();
envelope.addNamespaceDeclaration("tem", "http://tempuri.org/");
SOAPHeader sh = sm.getSOAPHeader();
SOAPBody sb = sm.getSOAPBody();
sh.detachNode();
QName bodyName = new QName(null, "setAMRequestData", "tem");
SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
QName n = new QName(null, "id", "tem");
SOAPElement quotation = bodyElement.addChildElement(n);
quotation.addTextNode("7028");
我在 SOAPElement quote = bodyElement.addChildElement(n); 行中遇到了以下异常:
org.w3c.dom.DOMException: NAMESPACE_ERR: 试图以不正确的命名空间方式创建或更改对象。
无论我如何尝试,我根本无法为 id 元素设置“tem”前缀......这是怎么回事?
谢谢。
【问题讨论】:
标签: java asp.net web-services soap soapui