我正在尝试在java中编写一些代码,以了解有关使用WSDL和SOAP进行编码的更多信息。
例如:
'<'to:checkAccount xmlns:to="http://foo"> '<'to:id> test '<'/to:id> '<'to:password> test '<'/to:password> '<'to:checkAccount >"
'<'element name="checkAccountResponse"> '<'complexType> '<'sequence> '<'element name="checkAccountReturn" type="impl:account"/> '<'/sequence> '<'/complexType> '<'/element>
'<'complexType name="account"> '<'sequence> '<'element name="active" type="xsd:boolean"/> '<'element name="name" type="xsd:string"/> '<'/sequence> '<'/complexType>
我的代码目前看起来像这样:
//create the message
String endpoint = "http://foo/someAPI";
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = message.getSOAPHeader();
//adding to the body
SOAPBody body = message.getSOAPBody();
SOAPFactory soapFactory = SOAPFactory.newInstance();
Name bodyName = soapFactory.createName("checkAccount","to","http://foo");
SOAPElement bodyElement = body.addBodyElement(bodyName);
//add the ID child elements
soapFactory = SOAPFactory.newInstance();
Name childName = soapFactory.createName("id","to","http://foo");
SOAPElement symbol = bodyElement.addChildElement(childName);
symbol.addTextNode("test");
//add password child element
soapFactory = SOAPFactory.newInstance();
childName = soapFactory.createName("password","to","http://foo");
symbol = bodyElement.addChildElement(childName);
symbol.addTextNode("test");
//call and get the response
SOAPMessage response = sc.call(message,endpoint);
//print the response
SOAPBody responseBody = response.getSOAPBody();
java.util.Iterator iterator = responseBody.getChildElements(bodyName);
.
.
.
//the response is blank so trying to iterate through it gives the exception
我跑了这个,我得不到任何回报,只是空白。我知道我的端点是正确的,以及checkAccount,id和密码,因为我已在xmlSpy中测试它并返回帐户状态。
它必须是我试图获得响应的方式。有人可以给我一个提示吗?
答案 0 :(得分:3)
我就是这样做的。
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPBody body = message.getSOAPBody();
SOAPElement checkAccEl = body
.addChildElement("checkAccount", "to", "http://foo");
SOAPElement idEl = checkAccEl
.addChildElement("id", "to", "http://foo");
idEl.addTextNode("test");
SOAPElement passwordEl = checkAccEl
.addChildElement("password", "to", "http://foo");
passwordEl.addTextNode("test");
// print out the SOAP Message. How easy is this?!
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
System.out.println(out.toString());
第一次使用名称空间'to = http://foo'时,它会自动在元素上声明 - 在这种情况下为checkAccount。当您再次使用相同的命名空间时,XML不需要再次声明它,而是使用前缀。
输出如下:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<to:checkAccount xmlns:to="http://foo">
<to:id>test</to:id>
<to:password>test</to:password>
</to:checkAccount>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
你想要的是什么