The Java EE 5 Tutorial

Request Example

The class Request puts together the code fragments used in the section SAAJ Tutorial and adds what is needed to make it a complete example of a client sending a request-response message. In addition to putting all the code together, it adds import statements, a main method, and a try/catch block with exception handling.

import javax.xml.soap.*;
import javax.xml.namespace.QName;
import java.util.Iterator;

public class Request {
    public static void main(String[] args)    {
        try {
            SOAPConnectionFactory soapConnectionFactory =
            SOAPConnection connection =

            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            SOAPHeader header = message.getSOAPHeader();
            SOAPBody body = message.getSOAPBody();

            QName bodyName = new QName("",
                "GetLastTradePrice", "m");
            SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

            QName name = new QName("symbol");
            SOAPElement symbol = bodyElement.addChildElement(name);

            URL endpoint = new URL("");
            SOAPMessage response =, endpoint);


            SOAPBody soapBody = response.getSOAPBody();

            Iterator iterator = soapBody.getChildElements(bodyName);
            bodyElement = (SOAPBodyElement);
            String lastPrice = bodyElement.getValue();

            System.out.print("The last price for SUNW is ");

        } catch (Exception ex) {

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.