Java Reference
In-Depth Information
QName bodyName = new QName(SERVICE_HOST, SERVICE_METHOD);
SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
SOAPElement soapBodyArgument1 = bodyElement.addChildElement("symbol");
soapBodyArgument1.addTextNode(stockSymbol);
// Add a SOAP action header to the request
// Action: http://www.webserviceX.NET/GetQuote
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", SERVICE_HOST + SERVICE_METHOD);
soapMessage.saveChanges();
return soapMessage;
}
private static void showSOAPResponse(SOAPMessage soapResponse)
throws Exception {
}
}
Let's start filling in this method. First, add the following two lines:
Node responseNode = soapResponse.getSOAPBody().getFirstChild();
System.out.println(responseNode.getTextContent());
This will take the SOAP body part from the response message (which is an XML document), and
then take the first child node in this body. Then you print the text content of this node, i.e., the text
between the tags in the XML message, which gives you the following:
<StockQuotes><Stock><Symbol>IBM</Symbol><Last>196.40</Last>
<Date>4/16/2014</Date><Time>4:01pm</Time><Change>-
0.62</Change><Open>197.77</Open><High>198.71</High><Low>195.00
</Low><Volume>8527415</Volume><MktCap>204.5B</MktCap>
<PreviousClose>197.02</PreviousClose><PercentageChange>-
0.31%</PercentageChange><AnnRange>172.19 - 211.98</AnnRange>
<Earns>14.942</Earns><P-E>13.19</P-E><Name>International
Bus</Name></Stock></StockQuotes>
You can see that Java has already “un‐escaped” the XML for you, but it is still regarded as one
big string. To parse this information, you need to construct a new object representing an XML
document out of this string, so you change the method to look like so:
private static void showSOAPResponse(SOAPMessage soapResponse) throws Exception {
Node responseNode = soapResponse.getSOAPBody().getFirstChild();
String xmlText = responseNode.getTextContent();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(
new StringReader(xmlText)));
}
Search WWH ::




Custom Search