Setting a custom HTTP header dynamically with Spring-WS client
public class AddHttpHeaderInterceptor implements ClientInterceptor {public boolean handleFault(MessageContext messageContext) throws WebServiceClientException { return true;}public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { TransportContext context = TransportContextHolder.getTransportContext(); HttpComponentsConnection connection =(HttpComponentsConnection) context.getConnection(); connection.addRequestHeader("name", "suman"); return true;}public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { return true;}}
config:
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate"> ... <property name="interceptors"> <list> <bean class="com.blah.AddHttpHeaderInterceptor" /> </list> </property></bean>
ClientInterceptor
works great for static header value. But it is not possible to use it when a different value should be applied per each request. In that case WebServiceMessageCallback
is helpful:
final String dynamicParameter = //...webServiceOperations.marshalSendAndReceive(request, new WebServiceMessageCallback() { void doWithMessage(WebServiceMessage message) { TransportContext context = TransportContextHolder.getTransportContext(); CommonsHttpConnection connection = (CommonsHttpConnection) context.getConnection(); PostMethod postMethod = connection.getPostMethod(); postMethod.addRequestHeader( "fsreqid", dynamicParameter ); }}
When using spring integration 3 and spring integration-ws, the following code can be used for handling the request:
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { TransportContext context = TransportContextHolder.getTransportContext(); HttpUrlConnection connection = (HttpUrlConnection) context .getConnection(); connection.getConnection().addRequestProperty("HEADERNAME", "HEADERVALUE"); return true;}
The Interceptor can be connected to the outbound gateway in the following way:
<ws:outbound-gateway ... interceptor="addPasswordHeaderInterceptor" ></ws:outbound-gateway><bean id="addPasswordHeaderInterceptor class="com.yourfirm.YourHttpInterceptor" />