More Complex Message Exchange

So far you have looked at simple message exchange. This section examines other issues when exchanging SOAP messages.

Headers and Attachments

As well as XML information in the SOAP body, SAAJ allows you to add and retrieve header information and attachments.

The SOAPHeader can be obtained from the SOAPEnvelope with the getHeader method. If you are creating a message, you can populate the header using the addHeaderElement method that returns a SOAPHeaderElement. You can then add text or attributes to this header element, as shown in the following:

Name txName = envelope.createName("TransactionId", "acme",
                                  "http://acme.com/transactions");
SOAPHeaderElement headerElement = header.addHeaderElement(txName);
headerElement.addTextNode("78d2892ea8af625323c7");

There are also specific methods for associating a particular SOAP actor or the SOAP mustUnderstand attribute to a header element.

When receiving a message, an Iterator can be retrieved with the examineHeaderElements method. This Iterator can be used to search through the header elements.

Additionally, you may want to add attachments to your SOAP messages containing non-XML data or additional XML documents. To do this, first create an instance of javax.xml.soap.AttachmentPart to attach to a message by using one of the createAttachmentPart methods on the SOAPMessage class. You can provide the data for your attachment directly (as a String or javax.xml.transform.Source) or through a content handler (part of the JavaBeans Activation Framework [JAF]). These attachments can be any form of data, so the key thing is to set the appropriate MIME type. If providing the data directly, you must specify the MIME type when creating the attachment. When using a content handler, this can supply the correct MIME type to the AttachmentPart object.

After you have created an AttachmentPart object, you attach it to the SOAP message using the addAttachmentPart method on the SOAPMessage class. The code required to create an attachment from an image at a given URL is shown in the following code:

SOAPMessage message = ...
...
URL url = new URL("http://acme.com/acme_logo.jpg");
AttachmentPart attachment = message.createAttachmentPart(new DataHandler(url));
message.addAttachmentPart(attachment);

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.86.154