简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM