Is it possible to add a Header to all outgoing cxf connections, from the client side.
Using Spring 3.0 and CXF 2.6.0
I would like to give my two cents here . I am solving the same case here in my post -
http://saurzcode.in/2014/05/08/adding-header-to-soap-request-using-cxf-2/
Spring Configuration :-
<jaxws:client id="mywebServiceClient"
serviceClass="com.saurzcode.TestService"
address="http://saurzcode.com:8088/mockTestService">
<jaxws:binding>
<soap:soapBinding version="1.2" mtomEnabled="true" />
</jaxws:binding>
</jaxws:client>
<cxf:bus>
<cxf:outInterceptors>
<bean class="com.saurzcode.ws.caller.SoapHeaderInterceptor" />
</cxf:outInterceptors>
</cxf:bus>
CXF Interceptor -
public class SoapHeaderInterceptor extends AbstractSoapInterceptor {
public SoapHeaderInterceptor() {
super(Phase.POST_LOGICAL);
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
List<Header> headers = message.getHeaders();
TestHeader testHeader = new TestHeader();
JAXBElement<TestHeader> testHeaders = new ObjectFactory()
.createTestHeader(testHeader);
try {
Header header = new Header(testHeaders.getName(), testHeader,
new JAXBDataBinding(TestHeader.class));
headers.add(header);
message.put(Header.HEADER_LIST, headers);
} catch (JAXBException e) {
e.printStackTrace();
}
}
I already know two ways of doing this. One is to create your SOAP Handler and register it as JAX-WS
handler in your Spring config.
Check my answer here how to create a SOAP handler. As you want header to appear in the response (outgoing request) don't forget that you then need to check if the message is outbound, something like this would do:
Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
//Modify your header.
}
The other, maybe more easier way. Put the header directly into CXF response context. Please note that this example is only proof of concepts, I don't know the situation in reality where you need credentials in the response. It will display how to add user credentials object into the header, you have to modify it depending on your needs.
private void modifyResponse(String username, String password) {
UserCredentials authHeader = new UserCredentials();
authHeader.setUsername(username);
authHeader.setPassword(password);
ArrayList<Header> headers = new ArrayList<Header>(1);
try {
Header soapHeader = new Header(
new QName("http://yournamespaceuri.com/something", "UserCredentials"),
authHeader,
new JAXBDataBinding(UserCredentials.class));
headers.add(soapHeader);
} catch (JAXBException ex) {
LOGGER.error("Exception trying to serialize header: {}", ex);
}
((BindingProvider) proxy).getResponseContext().put(Header.HEADER_LIST, headers);
}
This method needs to be called just after the request your client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With