background image

Header Example

<< Code Examples | Building and Running the Header Example >>
<< Code Examples | Building and Running the Header Example >>

Header Example

MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
header.detachNode();
QName bodyName = new QName(
"http://wombat.ztrade.com",
"GetLastTradePrice", "m");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
QName name = new QName(
"symbol");
SOAPElement symbol = bodyElement.addChildElement(name);
symbol.addTextNode(
"SUNW");
URL endpoint = new URL(
"http://wombat.ztrade.com/quotes");
SOAPMessage response = connection.call(message, endpoint);
connection.close();
SOAPBody soapBody = response.getSOAPBody();
Iterator iterator = soapBody.getChildElements(bodyName);
bodyElement = (SOAPBodyElement)iterator.next();
String lastPrice = bodyElement.getValue();
System.out.print(
"The last price for SUNW is ");
System.out.println(lastPrice);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
For the Request class to be runnable, the second argument supplied to the call method would
have to be a valid existing URI, and this is not true in this case.
Header Example
The example HeaderExample.java, based on the code fragments in the section
"Adding
Attributes" on page 603
, creates a message that has several headers. It then retrieves the contents
of the headers and prints them. The example generates either a SOAP 1.1 message or a SOAP
1.2 message, depending on arguments you specify. You will find the code for HeaderExample in
the following directory:
tut-install/javaeetutorial5/examples/saaj/headers/src/
Code Examples
The Java EE 5 Tutorial · September 2007
614