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):

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:

The handler resolver that is to contain the SOAP handler above looks like this:

Finally we need to add the handler resolver to our web service client class.

To find out how to generate the web service client classes check out this example:

Create a Web Service Client with JAX-WS

Search for more Java info on this site here:
Custom Search

6 thoughts on “Using a Message Handler to alter the SOAP Header in a Web Service Client

  1. Above code has helped me alot. But I made one small improvement to it, that might prohibit someone a headache.

    I am using it with GoogleWebToolkit. After I deployed and tested the project on a local Tomcat 7 server, the server crashed, because multiple headers were defined.

    In the HeaderHandler class, change following line:

    SOAPHeader header = envelope.addHeader();

    to the following lines:

    // Prevention for adding multiple headers.
    if (envelope.getHeader() == null)
    header = envelope.addHeader();
    header = envelope.getHeader();

    I hope it helps, thanks!

  2. Hi
    You’re using service.setHandlerResolver(handlerResolver); in the web service client class. But how does the service object get the method setHandlerResolver ???
    Very nice code by the way.

  3. Hi, thanks so much !! I’ve to add this in the
    public Set getHeaders() {
    // throw new UnsupportedOperationException(“Not supported yet.”);
    final QName securityHeader = new QName(
    “Security”, “wsse”);

    final HashSet headers = new HashSet();

    return headers;

Please type any questions here.