background image

Sending a Message

<< Getting a SOAPConnection Object | Adding Content to the Header >>
<< Getting a SOAPConnection Object | Adding Content to the Header >>

Sending a Message

To send a message, a SAAJ client can use a SOAPConnection object. A SOAPConnection object is
a point-to-point connection, meaning that it goes directly from the sender to the destination
(usually a URL) that the sender specifies.
The first step is to obtain a SOAPConnectionFactory object that you can use to create your
connection. The SAAJ API makes this easy by providing the SOAPConnectionFactory class
with a default implementation. You can get an instance of this implementation using the
following line of code.
SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
Now you can use soapConnectionFactory to create a SOAPConnection object.
SOAPConnection connection = soapConnectionFactory.createConnection();
You will use connection to send the message that you created.
Sending a Message
A SAAJ client calls the SOAPConnection method call on a SOAPConnection object to send a
message. The call method takes two arguments: the message being sent and the destination to
which the message should go. This message is going to the stock quote service indicated by the
URL
object endpoint.
java.net.URL endpoint = new URL(
"http://wombat.ztrade.com/quotes");
SOAPMessage response = connection.call(message, endpoint);
The content of the message you sent is the stock symbol SUNW; the SOAPMessage object
response
should contain the last stock price for Sun Microsystems, which you will retrieve in
the next section.
A connection uses a fair amount of resources, so it is a good idea to close a connection as soon as
you are finished using it.
connection.close();
Getting the Content of a Message
The initial steps for retrieving a message's content are the same as those for giving content to a
message: Either you use the Message object to get the SOAPBody object, or you access the
SOAPBody
object through the SOAPPart and SOAPEnvelope objects.
Then you access the SOAPBody object's SOAPBodyElement object, because that is the element to
which content was added in the example. (In a later section you will see how to add content
directly to the SOAPPart object, in which case you would not need to access the
SOAPBodyElement
object to add content or to retrieve it.)
SAAJ Tutorial
Chapter 19 · SOAP with Attachments API for Java
597