Apache CXF: How to add custom HTTP headers to a web service request?


HTTP header fields are components of the message header of requests and responses in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction, carry information about the client browser, the requested page, the server and more.

Here’s how the HTTP headers can be added to your web service calls made using CXF (I’m using CXF v2.4.0):

/**
* @author Singaram Subramanian
*
*/

/* Create a ClientProxyFactoryBean reference and assign it an instance of JaxWsProxyFactoryBean, a factory for creating JAX-WS proxies. This class provides access to the internal properties used to set-up proxies. Using it provides more control than the standard JAX-WS APIs. */

ClientProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(singz.ws.cxf.sample.SampleServiceInterface.class);

// Set the web service endpoint URL here
factory.setAddress("http://xxx.xxx.com/services/SampleService/v1");

SampleServiceInterface serviceClient = (SampleServiceInterface) factory.create();

// Get the underlying Client object from the proxy object of service interface
Client proxy = ClientProxy.getClient(serviceClient);

// Creating HTTP headers
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("XXX-SOA-SERVICE-NAME", Arrays.asList("SampleService"));
headers.put("XXX-SOA-APP-NAME", Arrays.asList("SampleServiceAppv1"));

// Add HTTP headers to the web service request
proxy.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);

// If you want to log the SOAP XML of outgoing requests and incoming responses at client side, you can leave this uncommented. It'll be helpful in debugging.
proxy.getOutInterceptors().add(new LoggingOutInterceptor());
proxy.getInInterceptors().add(new LoggingInInterceptor());

If you use CXF version less than 2.4.0 and you find that the custom headers are getting ignored, use MultivaluedMap. Have found a bug request in CXF help forum regarding this issue: Custom headers may get lost if CXF interceptors do not use MultivaluedMap (https://issues.apache.org/jira/browse/CXF-3408)

About these ads

One comment

  1. Abhi Rampal · · Reply

    Hi,

    I’m using cxf version 2.3.9, I have tried using MultivaluedMap but it seems that my custom headers are still getting ignored. Any chance you could direct my to an example using MultivaluedMap?

    Thanks in advance!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 26 other followers

%d bloggers like this: