background image

Sending the Request

<< SAAJ Client | Extracting the Price List >>
<< SAAJ Client | Extracting the Price List >>

Sending the Request

Accordingly, the client code has two major tasks. The first is to create and send the request; the
second is to extract the content from the response. These tasks are handled by the classes
PriceListRequest
and OrderRequest.
Sending the Request
This section covers the code for creating and sending the request for an updated price list. This
is done in the getPriceList method of PriceListRequest, which follows the DTD
price-list.dtd
.
The getPriceList method begins by creating the connection that will be used to send the
request. Then it gets the default MessageFactory object to be used for creating the SOAPMessage
object msg.
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
The next step is to access the message's SOAPBody object, to which the message's content will be
added.
SOAPBody body = msg.getSOAPBody();
The file price-list.dtd specifies that the topmost element inside the body is request-prices
and that it contains the element request. The text node added to request is the text of the
request being sent. Every new element that is added to the message must have a QName object to
identify it. The following lines of code create the top-level element in the SOAPBody object body.
The first element created in a SOAPBody object is always a SOAPBodyElement object.
Name bodyName = new QName(
"http://sonata.coffeebreak.com",
"request-prices", "RequestPrices");
SOAPBodyElement requestPrices =
body.addBodyElement(bodyName);
In the next few lines, the code adds the element request to the element request-prices
(represented by the SOAPBodyElement requestPrices). Then the code adds a text node
containing the text of the request. Next, because there are no other elements in the request, the
code calls the method saveChanges on the message to save what has been done.
QName requestName = new QName(
"request");
SOAPElement request = requestPrices.addChildElement(requestName);
request.addTextNode(
"Send updated price list.");
msg.saveChanges();
SAAJ Coffee Supplier Service
The Java EE 5 Tutorial · September 2007
1034