Thursday, January 10, 2008

Sending a custom soap header to a Web Service

Sometimes Web Services require sending information through soap headers.It is quite simple and easy to send a custom soap header using WSF/PHP.

Consider we want to send a soap header "Transaction" with like in the following soap envelope.

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Header>
<t:Transaction soapenv:mustUnderstand="1" xmlns:t="Some-URI">5</t:Transaction>
</soapenv:Header>
<soapenv:Body>
<ns1:Greet xmlns:ns1="http://php.axis2.org/samples">
<text>Hello</text>
</ns1:Greet>
</soapenv:Body>
</soapenv:Envelope>

First we will create a WSHeader object to produce this header.

$header = WSHeader("ns"=>"some-URI",
"prefix"=>"t",
"name"=>"Transaction",
"data"=>"5",
"mustUnderstand"=>"true");

Now lets create a WSMessage object and set the header to the inputHeaders array.

$msg = new WSMessage($requestPayloadString,
array("inputHeaders" => array($header)));

Note that $requestPayloadString holds the payload string that will be sent to the service.


Following is the complete source code.

$requestPayloadString = <<<XML
<ns1:Greet xmlns:ns1="http://php.axis2.org/samples">
<text>Hello</text>
</ns1:Greet>
XML;

try {

$client = new WSClient(array ("to"=>"http://localhost/samples/greet_service.php"));


$header = WSHeader("ns"=>"some-URI",
"prefix"=>"t",
"name"=>"Transaction",
"data"=>"5");

$msg = new WSMessage($requestPayloadString ,
array("inputHeaders" => array($header)));

$client->request($msg);

echo "\n\n Received message \n";
echo htmlspecialchars($recvMsg);

} catch (Exception $e) {
if ($e instanceof WSFault) {
printf("Soap Fault: %s\n", $e->Reason);
} else {
printf("Message = %s\n",$e->getMessage());
}
}

2 comments:

  1. Can you provide any information on the class you're using to produce WSHeader?

    ReplyDelete
  2. Mr. Nandika
    Sorry for my English!
    I can do this with a wsdl mode

    ReplyDelete