O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Headers to a SOAP Request

Problem

You want to add custom header information to a SOAP request using JAX-WS.

Solution

There are a few basic ways to do this. You can use the SAAJ API, which ensures portability, and add the headers to your code on invocation. Alternatively, depending on the structure of the WSDL you have to invoke, you can create a Holder<T> that will add the headers as message parameters.

You can also use vendor-specific convenience code for this. With Metro, for example, you can use Headers.create.

Discussion

We’ll look at these alternatives here.

A new option, -XadditionalHeaders, was added to the wsimport task in JAX-WS RI 2.1.3. This option automatically maps headers as method parameters. You may have a slightly earlier version of Java, such as 2.1.1, that does not support this.

Note

If you are using CXF, you can specify -exsh true instead.

Let’s say that you have the following simple WSDL defined:

<message name="usernameHeader">
    <part name="usernameHeader" element="types:usernameHeader"/>
</message>

<wsdl:portType name="SecureCatalogPortType">
    <wsdl:operation name="execute">
        <wsdl:input message="tns:aRequest"/>
        <wsdl:output message="tns:aResponse"/>
    </wsdl:operation>
</wsdl:portType>
                
<wsdl:binding name="SecureCatalogBinding" type="tns:SecureCatalogPortType">
     <soap:binding style="document" 
       transport="http://schemas.xmlsoap.org/soap/http"/>
     <wsdl:operation name="execute">
        <soap:operation/>
        <wsdl:input>
            <soap:body message="tns:aRequest"/>
            <soap:header message="tns:usernameHeader" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required