Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SOAP headers

Here is the request

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:soap="http://soap.ws.server.wst.fit.cvut.cz/">
    <soapenv:Header>
        <userId>someId</userId>
    </soapenv:Header>
    <soapenv:Body>
    ...
    </soapenv:Body>
</soapenv:Envelope>

and I want to get that userId.

I tried this

private List<Header> getHeaders() {
    MessageContext messageContext = context.getMessageContext();
    if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) {
        return null;
    }
    Message message = ((WrappedMessageContext) messageContext).getWrappedMessage();
    return CastUtils.cast((List<?>) message.get(Header.HEADER_LIST));
}

private String getHeader(String name) {
    List<Header> headers = getHeaders();
    if (headers != null) {
        for (Header header : headers) {
            logger.debug(header.getObject());
            // return header by the given name                   
        }
    }
    return null;
}

And it logs [userId : null]. How can I get the value and why is null there?

like image 617
user219882 Avatar asked Dec 03 '22 04:12

user219882


2 Answers

"[userId : null]" is generally the "toString" printout of a DOM element. Most likely if you do something like

logger.debug(header.getObject().getClass())

you will see that it is a DOM Element subclass of somesort. Thus, something like:

logger.debug(((Element)header.getObject()).getTextContent())

might print the text node.

like image 64
Daniel Kulp Avatar answered Dec 09 '22 14:12

Daniel Kulp


    import javax.xml.soap.*;

    SOAPPart part = request.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPHeader header = env.getHeader();
    if (header == null) {
        // Throw an exception
     }

    NodeList userIdNode = header.getElementsByTagNameNS("*", "userId");
    String userId = userIdNode.item(0).getChildNodes().item(0).getNodeValue();
like image 40
Adedhela Avatar answered Dec 09 '22 16:12

Adedhela