Using a Message Handler to alter the SOAP Header in a Web Service Client

Sometimes you need to insert information in the soap header when calling a web service. Perhaps the service needs authentication information that needs to be set. This example shows how to set the security information for a Web Service that is deployed on a Weblogic server using JAX-WS and SAAJ. First we need to create the actual handler which implements the SOAPHandler interface. Next we need to create the class that implements the HandlerResolver interface. This class decides what handlers should be called and in what specific order. The handler above is added to this class. Finally we need to add the HandlerResolver instance to the Web Service Client. By default the SOAP header is empty, but this is what we want the header to look like on the outbound call (the call to the web service):


                                   
                                        
               TestUser
               TestPassword
          
     

In our handler we need to do the implementation of a few methods but it is only the handleMessage() method that is of essence here. This is what our handler class looks like:
package com.javadb.ws.example;

import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandler implements SOAPHandler {

    public boolean handleMessage(SOAPMessageContext smc) {

        Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {

            SOAPMessage message = smc.getMessage();

            try {

                SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.addHeader();

                SOAPElement security =
                        header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

                SOAPElement usernameToken =
                        security.addChildElement("UsernameToken", "wsse");
                usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

                SOAPElement username =
                        usernameToken.addChildElement("Username", "wsse");
                username.addTextNode("TestUser");

                SOAPElement password =
                        usernameToken.addChildElement("Password", "wsse");
                password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
               password.addTextNode("TestPassword");

                //Print out the outbound SOAP message to System.out
                message.writeTo(System.out);
                System.out.println("");
                
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            try {
                
                //This handler does nothing with the response from the Web Service so
                //we just print out the SOAP message.
                SOAPMessage message = smc.getMessage();
                message.writeTo(System.out);
                System.out.println("");

            } catch (Exception ex) {
                ex.printStackTrace();
            } 
        }


        return outboundProperty;

    }

    public Set getHeaders() {
        //throw new UnsupportedOperationException("Not supported yet.");
        return null;
    }

    public boolean handleFault(SOAPMessageContext context) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return true;
    }

    public void close(MessageContext context) {
    //throw new UnsupportedOperationException("Not supported yet.");
    }
}
The handler resolver that is to contain the SOAP handler above looks like this:
package com.javadb.ws.example;

import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandlerResolver implements HandlerResolver {
    
public List getHandlerChain(PortInfo portInfo) {
      List handlerChain = new ArrayList();

      HeaderHandler hh = new HeaderHandler();

      handlerChain.add(hh);

      return handlerChain;
   }
}
Finally we need to add the handler resolver to our web service client class.
   JavadbWebServiceService service = new JavadbWebServiceService();

   HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
   service.setHandlerResolver(handlerResolver);

   JavadbWebService port = service.getJavadbWebServicePort();
        
   //Call web service
   String currentTime = port.getTime();
        
   System.out.println("Current time is: " + currentTime);
To find out how to generate the web service client classes check out this example: Create a Web Service Client with JAX-WS

This is an article from http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client

4 comentários:

Fabio De Carli disse...

http://examples.javacodegeeks.com/enterprise-java/jws/jax-ws-soap-handler-example/

Sunny Frozen disse...

You can market your product/brand through
outbound call service provided by Convex Interactive. Outbound campaigns is a good technique to have an significant impact on the consumer.

Anónimo disse...

Thanks. Working fine.

If application throwing below exception "com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present."

Please use SOAPHeader header = envelope.getHeader() instead of
SOAPHeader header = envelope.addHeader()

Amauri disse...

Thank you very much, Fabio de Carli, this example did not work here, but the link that sent worked like a charm!

Enviar um comentário