how to set soap Header using ksoap2 - android

user698555 picture user698555 · Apr 10, 2011 · Viewed 22.8k times · Source

I need to set the soap header information as part of authentication of a web method. I'm using ksoap2 API to call .NET web service. Here is the soap header with request.

<soap:Header>
    <DTHeader xmlns="http://myServer.com/webservices/">
      <Username> string </Username>
      <Password> string </Password>
    </DTHeader>
</soap:Header>
<soap:Body>
    <MyTestMethod xmlns="http://myServer.com/webservices/">
       <ID> string </ID>
       <TransID> guid </TransID>
     </MyTestMethod>
</soap:Body>

Can you please provide the android code to set the soap header "DTHeader" and set "Username" and "Password".

Answer

bigstones picture bigstones · Apr 10, 2011

I did that this way:

import org.kxml2.kdom.Element;

then while preparing envelope

soapEnvelope.headerOut = new Element[1];
soapEnvelope.headerOut[0] = buildAuthHeader();
// ...send request...

with

private Element buildAuthHeader() {
    Element h = new Element().createElement(NAMESPACE, "AuthHeader");
    Element username = new Element().createElement(NAMESPACE, "user");
    username.addChild(Node.TEXT, USERNAME);
    h.addChild(Node.ELEMENT, username);
    Element pass = new Element().createElement(NAMESPACE, "pass");
    pass.addChild(Node.TEXT, PASSWORD);
    h.addChild(Node.ELEMENT, pass);

    return h;
}

obviously, change strings as needed.