Adding SOAP Header in Java

Simple minimal code to add your own SOAP header

// Security	token
String token;
// MyService and MySoapService are stubs generated from WSDL
MyService service = new MyService();
MyServiceSoap ep = service.getMyServiceSoap();

Binding binding = ((BindingProvider) ep).getBinding();
List handlers = binding.getHandlerChain();
handlers.add(new MySOAPHandler(token));

Here is the code of the MySOAPHandler class used to intercept messages and actually add SOAP header

public class MySOAPHandler implements SOAPHandler {

	private String token;

	public DHSOAPHandler(String token) {
		this.token = token;
	public boolean handleMessage(SOAPMessageContext messageContext) {
		msg = messageContext.getMessage();
		if ((Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)){
			try {
				SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
				SOAPHeader header = envelope.addHeader();
				SOAPElement el = header.addHeaderElement(envelope.createName("TicketHeader",
									"", ""));
				el = el.addChildElement(envelope.createName("Ticket", "", ""));
			catch (SOAPException	e) {
				return false;
		return true;

	public boolean handleFault(SOAPMessageContext messageContext) {
		return true;

	public void close(MessageContext messageContext){
	// I'm not quite sure about what should this function do, but I guess something like this...
	public Set getHeaders(){
		Set headers = new HashSet();
		headers.add(new QName("", "TicketHeader"));
		return headers;

The structure of the header to be added is



4 thoughts on “Adding SOAP Header in Java

  1. Hi There,

    Thank you so much for your post, I was looking for the same thing for days…

    I need a help, could you please post or send the source of a sample TestApp of the above program. It would be really help full. my email id is


Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s