API说我必须使用“getStock”方法和以下参数: 的accessToken,公司,itemNumber,commissionNumber。 我写了这段代码,但它不起作用。
SOAPEnvelope envelope = soapPart.getEnvelope();
//envelope.addNamespaceDeclaration("sam", "http://samples.axis2.techdive.in");
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement method = soapBody.addChildElement("getStock");
SOAPElement firstParam = method.addChildElement("accessToken");
firstParam.addTextNode("xxx");
SOAPElement secondParam = method.addChildElement("company");
secondParam.addTextNode("AS");
SOAPElement thirdParam = method.addChildElement("itemNumber");
thirdParam.addTextNode("020001");
SOAPElement fourthParam = method.addChildElement("commissionNumber");
fourthParam.addTextNode("0");
soapMessage.saveChanges();
那么NamespaceDeclaration呢?
我收到此错误:
响应SOAP消息= NS2:客户端 找不到{} getStock的调度方法 处理以退出代码0结束
问候安德鲁
答案 0 :(得分:1)
为了指定前缀和名称空间,您可以使用Qname
对象(import javax.xml.namespace.QName;)
,如下所示:
QName stockQname = new QName("http://your_namespace_uri.com",
"getStock", "prefix");
将prefix
更改为您的实际前缀。
将命名空间更改为实际的namespaceuri
我重写了你的代码以使用Qnames:
private static void test() throws SOAPException {
MessageFactory factory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
QName stockQname = new QName("http://your_namespace_uri.com",
"getStock", "prefix");
SOAPBodyElement stockElement = soapBody.addBodyElement(stockQname);
QName accessQname = new QName("accessToken");
SOAPElement accessElement = stockElement.addChildElement(accessQname);
accessElement.addTextNode("xxx");
QName companyQname = new QName("company");
SOAPElement companyElement = stockElement.addChildElement(companyQname);
companyElement.addTextNode("AS");
QName itemQname = new QName("itemNumber");
SOAPElement itemElement = stockElement.addChildElement(itemQname);
itemElement.addTextNode("020001");
QName commisionQname = new QName("commissionNumber");
SOAPElement commissionElement = stockElement
.addChildElement(commisionQname);
commissionElement.addTextNode("0");
message.saveChanges();
}
这是生成的SOAP消息:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<prefix:getStock xmlns:prefix="http://your_namespace_uri.com">
<accessToken>xxx</accessToken>
<company>AS</company>
<itemNumber>020001</itemNumber>
<commissionNumber>0</commissionNumber>
</prefix:getStock>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
我正在使用这个SAAJ库
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.3.25</version>
</dependency>
如果要使用SOAP 1.2消息协议,只需更改以下行:
MessageFactory factory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
到这一行:
MessageFactory factory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
希望这有帮助