How do you set a custom HTTP header (not SOAP header) dynamically on the client side when using Spring-WS?
Example Method with java 1.8: How to add a HTTP header:
public void executeObjectWebservice(String id) {
ExecuteObject request = new ExecuteObject();
getWebServiceTemplate().marshalSendAndReceive("http://url/webservice-test/uc4ws",
new ObjectFactory().createExecuteObject(request), new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) throws IOException {
TransportContext context = TransportContextHolder.getTransportContext();
HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
connection.addRequestHeader("ID", id);
}
});
}
Explanation: Use the getWebServiceTemplate().marshalSendAndReceive as described for example here: https://spring.io/guides/gs/consuming-web-service/
First parameter is the URI, second is the object which shall be send with the request. As third Parameter you can add as function
new WebServiceMessageCallback()
where you override the public void doWithMessage
. This method gets called before the request is sent. Within you can access the message and add a request Header through
TransportContext context = TransportContextHolder.getTransportContext();
HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
connection.addRequestHeader("ID", id);