Using a Message Handler to alter the SOAP Header in a Web Service Client

Sometimes you need to insert information in the soap header when calling a web service. Perhaps the service needs authentication information that needs to be set. This example shows how to set the security information for a Web Service that is deployed on a Weblogic server using JAX-WS and SAAJ. First we need to create the actual handler which implements the SOAPHandler interface. Next we need to create the class that implements the HandlerResolver interface. This class decides what handlers should be called and in what specific order. The handler above is added to this class. Finally we need to add the HandlerResolver instance to the Web Service Client. By default the SOAP header is empty, but this is what we want the header to look like on the outbound call (the call to the web service):


                                   
                                        
               TestUser
               TestPassword
          
     

In our handler we need to do the implementation of a few methods but it is only the handleMessage() method that is of essence here. This is what our handler class looks like:
package com.javadb.ws.example;

import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandler implements SOAPHandler {

    public boolean handleMessage(SOAPMessageContext smc) {

        Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {

            SOAPMessage message = smc.getMessage();

            try {

                SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.addHeader();

                SOAPElement security =
                        header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

                SOAPElement usernameToken =
                        security.addChildElement("UsernameToken", "wsse");
                usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

                SOAPElement username =
                        usernameToken.addChildElement("Username", "wsse");
                username.addTextNode("TestUser");

                SOAPElement password =
                        usernameToken.addChildElement("Password", "wsse");
                password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
               password.addTextNode("TestPassword");

                //Print out the outbound SOAP message to System.out
                message.writeTo(System.out);
                System.out.println("");
                
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            try {
                
                //This handler does nothing with the response from the Web Service so
                //we just print out the SOAP message.
                SOAPMessage message = smc.getMessage();
                message.writeTo(System.out);
                System.out.println("");

            } catch (Exception ex) {
                ex.printStackTrace();
            } 
        }


        return outboundProperty;

    }

    public Set getHeaders() {
        //throw new UnsupportedOperationException("Not supported yet.");
        return null;
    }

    public boolean handleFault(SOAPMessageContext context) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return true;
    }

    public void close(MessageContext context) {
    //throw new UnsupportedOperationException("Not supported yet.");
    }
}
The handler resolver that is to contain the SOAP handler above looks like this:
package com.javadb.ws.example;

import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandlerResolver implements HandlerResolver {
    
public List getHandlerChain(PortInfo portInfo) {
      List handlerChain = new ArrayList();

      HeaderHandler hh = new HeaderHandler();

      handlerChain.add(hh);

      return handlerChain;
   }
}
Finally we need to add the handler resolver to our web service client class.
   JavadbWebServiceService service = new JavadbWebServiceService();

   HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
   service.setHandlerResolver(handlerResolver);

   JavadbWebService port = service.getJavadbWebServicePort();
        
   //Call web service
   String currentTime = port.getTime();
        
   System.out.println("Current time is: " + currentTime);
To find out how to generate the web service client classes check out this example: Create a Web Service Client with JAX-WS

This is an article from http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client

176 comentários:

Unknown disse...

http://examples.javacodegeeks.com/enterprise-java/jws/jax-ws-soap-handler-example/

Anónimo disse...

Thanks. Working fine.

If application throwing below exception "com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present."

Please use SOAPHeader header = envelope.getHeader() instead of
SOAPHeader header = envelope.addHeader()

Amauri disse...

Thank you very much, Fabio de Carli, this example did not work here, but the link that sent worked like a charm!

Unknown disse...

Thanks @Anónimo. The change you suggested saved me days of pain.

Unknown disse...

Hi,
Thank you for you post it is useful for me to add header. but while using ws-import not able to handle a response below exception is thrown.

Exception in thread "main" com.sun.xml.internal.ws.protocol.soap.MessageCreationException: Couldn't create SOAP message due to exception: XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.

Hope you help to find solution on these
Thanks
Tanmay
tanmaysonawane72@gmail.com

Unknown disse...

It works for me:

if (envelope.getHeader() != null) {
envelope.getHeader().detachNode();
}
SOAPHeader header = envelope.addHeader();

Anónimo disse...

aumentar tamaño del pene

Anónimo disse...

Phyton Gel opinion

Anónimo disse...

farmaci per la disfunzione erettile

Anónimo disse...

penis enlargement nhs

Anónimo disse...

aumento tamaño pene

Anónimo disse...

was tun bei impotenz

Anónimo disse...

bessere erektionen

Anónimo disse...

Elongattor où acheter ?

Anónimo disse...

Member xxl

Anónimo disse...

https://nuovo-inizio.com/

Anónimo disse...

Armostrax Opiniones

Anónimo disse...

BeMass ¿Dónde Comprarlo

Anónimo disse...

Muscle Pro Xtreme composición

Anónimo disse...

Erogan

Anónimo disse...

eron plus

Anónimo disse...

https://nuevo-comienzo.com/

Anónimo disse...

Erogan

Anónimo disse...

https://nuovo-inizio.com/peperoncino-per-il-dimagrimento/

Anónimo disse...

Potencialex opinion

Anónimo disse...

https://nuevo-comienzo.com/dieta-cetogenica/

Anónimo disse...

Virility EX fonctionnement

Anónimo disse...

http://penis-enlargement-tablets2020.com/

Anónimo disse...

Titan Gel Où Acheter

Anónimo disse...

Member xxl

Anónimo disse...

https://nuevo-comienzo.com/metodos-comprobados-para-eliminar-el-exceso-de-grasa/

Anónimo disse...

https://nuovo-inizio.com/fast-burn-extreme/

Anónimo disse...

eroxel

Anónimo disse...

Member XXL

Anónimo disse...

Atlant Gel

Anónimo disse...

https://nuovo-inizio.com/curcuma/

Anónimo disse...

https://nuovo-inizio.com/dieta-chetogenica/

Anónimo disse...

https://nuovo-inizio.com/come-si-puo-perdere-peso-dalla-pancia-e-al-girovita-rapidamente/

Anónimo disse...

http://ranking-dla-kulturystow.eu/co-jesc-aby-miesnie-szybciej-rosly.html

Anónimo disse...

http://top3-muscle-mass-supplements.com/provide-the-protein-and-enjoy-the-perfect-body.html

Anónimo disse...

https://the-new-beginning.co.uk/methods-to-eliminate-excessive-fat/

Anónimo disse...

was tun gegen impotenz

Anónimo disse...

http://top3-muscle-mass-supplements.com/how-to-improve-the-appearance-of-your-muscles.html

Anónimo disse...

https://nuovo-inizio.com/10-metodi-provati-per-eliminare-il-grasso-in-eccesso/

Anónimo disse...

https://nuevo-comienzo.com/pimiento-para-perder-peso/

Anónimo disse...

HTTP://TOP3-MUSCLE-MASS-SUPPLEMENTS.COM/HOW-TO-DEVELOP-DREAM-WEIGHT-QUICKLY.HTML

Anónimo disse...

https://nuevo-comienzo.com/estoy-a-dieta-pero-no-puedo-perder-peso/

Anónimo disse...

integratori massa magra

Anónimo disse...

tabletten für muskelaufbau

Anónimo disse...

pastillas para aumentar el libido

Anónimo disse...

green barley plus

Anónimo disse...

Potencialex composizione

Anónimo disse...

augmenter sa force en musculation

Anónimo disse...

integratori per massa muscolare naturali

Anónimo disse...

Maca du Pérou Fonctionnement

Anónimo disse...

que manger pour prendre de la masse musculaire

Anónimo disse...

prodotti per aumentare massa muscolare velocemente

Anónimo disse...

steroide tabletten

Anónimo disse...

ciclo steroidi

Anónimo disse...

dieta para ganar masa muscular sin grasa hombre

Anónimo disse...

aumentar masa muscular suplementos

Anónimo disse...

migliori integratori per aumentare la massa muscolare

Anónimo disse...

aumentare massa muscolare velocemente

Anónimo disse...

odzywki na mase miesniowa

Anónimo disse...

ganar musculo limpio

Anónimo disse...

http://penisverlangerung-pillen-de.eu/titan-gel.html

Anónimo disse...

http://penisznovelo-eljarasok-hu.eu/atlant-gel.html

Anónimo disse...

fast burn extreme foro

Anónimo disse...

http://best-slimming-pills-ranking.co.uk/pills-ranking.html

Anónimo disse...

http://potency-pills-ranking.co.uk/

Anónimo disse...

http://potency-pills-ranking.co.uk/erogan.html

Anónimo disse...

http://penisznovelo-eljarasok-hu.eu/erogan.html

Anónimo disse...

http://penisznovelo-eljarasok-hu.eu/Beast-Gel.html

Anónimo disse...

http://muscle-mass-suplemetns.co.uk/nutrigo-lab-mass.html

Anónimo disse...

http://potenspiller2017.ovh/erogan.html

Anónimo disse...

http://muscle-mass-suplemetns.co.uk/steroids.html

Anónimo disse...

http://penisznovelo-eljarasok-hu.eu/machoman.html

Anónimo disse...

http://bigger-penis-pills.co.uk/vigRX.html

Anónimo disse...

http://bigger-penis-pills.co.uk/titan-gel.html

Anónimo disse...

http://penisverlangerung-pillen-de.eu/turbomaxblue.html

Anónimo disse...

http://best-slimming-pills-ranking.co.uk/ketogenic-diet.html

Anónimo disse...

http://penisverlangerung-pillen-de.eu/Penilux-Gel.html

Anónimo disse...

http://bigger-penis-pills.co.uk/erogan.html

Anónimo disse...

http://potenspiller2017.ovh/Potensproblem.html

Anónimo disse...

http://potenzmittel-online-bestellen-de.eu/erectonin.html

Anónimo disse...

http://najlepszetabletkinamase.eu/Nutrigo-Lab-Burner.html

Anónimo disse...

http://odchudzanka.pl/black-latte-dzialanie-sklad-opinie-cena-i-gdzie-kupic/

Anónimo disse...

http://jak-prodlouzit-penis-cz.eu/memberxxl.html

Anónimo disse...

http://tabletky-na-erekci-cz.eu/eronplus.html

Anónimo disse...

http://jak-prodlouzit-penis-cz.eu/eroxel.html

Anónimo disse...

http://potenspiller2017.ovh/machoman-eller-eron-plus.html

Anónimo disse...

http://ranking-powiekszanie-penisa.eu/Erogan.html

Anónimo disse...

http://potenzmittel-online-bestellen-de.eu/Erofertil.html

Anónimo disse...

http://jak-prodlouzit-penis-cz.eu/turbomaxblue.html

Anónimo disse...

http://tabletky-na-rast-penisu-sk.eu/TurboMaxBlue.html

Anónimo disse...

profolan

Anónimo disse...

http://tabletky-na-erekci-cz.eu/tonus-fortis.html

Anónimo disse...

http://ranking-powiekszanie-penisa.eu/TurboMaxBlue.html

Anónimo disse...

vitamine et minéraux musculation

Anónimo disse...

prodotto che fa crescere i capelli

Anónimo disse...

comment se muscler

Anónimo disse...

εροφερτιλ

Anónimo disse...

viagra erfahrungsberichte

Anónimo disse...

sensamax apotheke

Anónimo disse...

trattamento ricrescita capelli uomo

Anónimo disse...

beste diät tabletten

Anónimo disse...

xtrazex tabletten erfahrung

Anónimo disse...

consecuencias de consumir erogan

Anónimo disse...

potencialex bestellen

Anónimo disse...

come aumentare la massa muscolare in poco tempo

Anónimo disse...

viril max pareri forum

Anónimo disse...

so war der sex mit xxl penis

Anónimo disse...

xxl.se

Anónimo disse...

eroxel

Anónimo disse...

comment bien maigrir

Anónimo disse...

member xxl gebruiksaanwijzing

Anónimo disse...

potenshöjande tabletter

Anónimo disse...

se poate mari penisul

Anónimo disse...

powiekszanie biustu tluszczem poznań

Anónimo disse...

erozon max fa male

Anónimo disse...

yerba mate najlepsza

Anónimo disse...

xxl pene

Anónimo disse...

tabletki na spalanie tłuszczu z brzucha

Anónimo disse...

cura anticaduta capelli

Anónimo disse...

viagra uomo

Anónimo disse...

testo booster migliore

Anónimo disse...

testerone booster

Anónimo disse...

penisvergroting voor en na

Anónimo disse...

crescita muscolare rapida

Anónimo disse...

maxman capsulas

Anónimo disse...

testo ultra pagina oficial

Anónimo disse...

creme agrandissement penis

Anónimo disse...

dieta per fare massa muscolare

Anónimo disse...

produit pour endurance au lit

Anónimo disse...

dr extenda avis

Anónimo disse...

jak zbudować masę mięśniową

Anónimo disse...

muskelaufbau präparat

Anónimo disse...

https://the-new-beginning.co.uk/ranking-of-slimming-pills/

Anónimo disse...

kreatyna białko

Anónimo disse...

trogaine

Anónimo disse...

https://uj-kezdet.com/a-fogyokuras-tablettak-rangsorolasa/

Anónimo disse...

https://nuovo-inizio.com/classifica-delle-pillole-dimagranti/

Anónimo disse...

productos cabello

Anónimo disse...

http://tabletky-na-zvacsenie-penisu.com/

Anónimo disse...

http://pastillas-para-agrandar-el-pene-es.eu

Anónimo disse...

slimming tablets that work uk

Anónimo disse...

weight loss pills uk

Anónimo disse...

penis enlargement ayurvedic oil

Anónimo disse...

best slimming tablets

Anónimo disse...

keto plus virker det

Anónimo disse...

keto actives erfahrungen

Anónimo disse...

mejores pastillas para adelgazar rapido

Anónimo disse...

http://penisverlangerung-pillen-de.eu/

Anónimo disse...

penisverdickung

Anónimo disse...

http://basta-testosteronboosters-se.eu

Anónimo disse...

http://ranking-powiekszanie-penisa.eu

Anónimo disse...

http://potens-piller-dk.eu

Anónimo disse...

http://produits-minceur-2020.eu

Anónimo disse...

https://zacznijodnowa.com.pl

Anónimo disse...

http://umbb-handball.fr/

Anónimo disse...

http://www.swift-italia.it/

Anónimo disse...

http://nnet.it/

Anónimo disse...

http://nl.global-box.net/

Anónimo disse...

http://mocinfo.org/kondom-xl/

Anónimo disse...

http://mocinfo.org/pennis-vergrosern/

Anónimo disse...

http://bkproma.it/come-far-allungare-il-pene/

Anónimo disse...

http://bkproma.it/metodi-masturbazione-femminile/

Anónimo disse...

http://pillole-per-dimagrire-che-funzionano2018.ovh

Anónimo disse...

http://pillole-per-pene-it.eu

Anónimo disse...

http://speed-com.fr/chorro-el-macho/

Anónimo disse...

http://los-mejores-boosters-de-testosterona-es.eu

Anónimo disse...

http://intecum.fr

Anónimo disse...

Различные типы предсказания грядущего обозначают как мистические учения. Конкретный образ предсказания судьбы исключительный и подготовлен для различных задач. Что он хочет от отношений гадание на любимого на Таро и достоверность ворожения в основном зависит от опыта человека. Любой хочет знать свою судьбу и воспринимает конкретные варианты гадания по максимуму действенными.

Eslam disse...

Really appreciated.

this worked with me
public class HeaderHandler implements SOAPHandler {
instead of this
public class HeaderHandler implements SOAPHandler {

Anónimo disse...

В настоящее время 99% всех коммерческих договоренностей происходят в инете. На сайте гидра официальный сайт вы сможете отыскать продукты на индивидуальный вкус и стоимость. Маркет реализует продукцию уже более 6 лет, и за такой отрезок времени сумел охарактеризовать себя как крутая торговая платформа. Гидра – это современный интернет-магазин, на каком доступно купить требуемые продукты по действительно выгодной цене.

Digisol Hub disse...

DigisolHub
Digisol Hub is a Digital Marketing & Tech. Company, that provides solutions regarding website development, SEO, Social Media Marketing, Google Ads, and Graphics designing, App development, Software development, Website Development. We just want to solve the problems of the people by using the right digital marketing strategy and give them Value so that they can build their business in the Online world.

Enviar um comentário