How to get header elements name and value from SOAP header?

haja picture haja · Aug 24, 2015 · Viewed 8k times · Source

How can I get userID and password tag name and value from soap request Header.

My request xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://WS.com/">
<soapenv:Header>
<userID>34</userID>
<password>test</password>
</soapenv:Header>
<soapenv:Body>
</soapenv:Body>
</soapenv:Envelope>

My java code

MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart  soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();

i want to get userID and password to validate the request.

Please help

Thanks

Answer

Tim Biegeleisen picture Tim Biegeleisen · Aug 24, 2015

Try using this code:

// raw SOAP input as String
String input = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://WS.com/\">"
             + "<soapenv:Header>"
             + "<userID>34</userID>"
             + "<password>test</password>"
             + "</soapenv:Header>"
             + "<soapenv:Body>"
             + "</soapenv:Body>"
             + "</soapenv:Envelope>";

// Use MessageFactory with raw input as byte array
InputStream is = new ByteArrayInputStream(input.getBytes());
SOAPMessage message = MessageFactory.newInstance().createMessage(null, is);
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();

// obtain all Nodes tagged 'userID' or 'password'
NodeList userIdNode = header.getElementsByTagNameNS("*", "userID");
NodeList passwordNode = header.getElementsByTagNameNS("*", "password");

// extract the username and password
String userId = userIdNode.item(0).getChildNodes().item(0).getNodeValue();
String password = passwordNode.item(0).getChildNodes().item(0).getNodeValue();

System.out.println("userID: " + userId);
System.out.println("password: " + password);

Output:

userID: 34
password: test