Apache CXF: How to add custom HTTP headers to a web service request?
Join the DZone community and get the full member experience.
Join For FreeHTTP 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());
f 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)
From http://singztechmusings.wordpress.com/2011/09/17/apache-cxf-how-to-add-custom-http-headers-to-a-web-service-request/
Opinions expressed by DZone contributors are their own.
Comments