L
L
lezhenkin2020-02-19 00:19:11
PHP
lezhenkin, 2020-02-19 00:19:11

How to add HTTP headers to SOAP request?

From a PHP script, I am sending a SOAP request. In addition to the data in the request body, the server expects two more HTTP headers from me. I can't figure out how to send them to him correctly.

What am I doing.

$oSoapClient = new SoapClient( $url, $aOptions );

$aHeaders = array();
$aHeaders[] = new SoapHeader( 'http://soapinterop.org/echoheader/', 'token', $token ); 
$aHeaders[] = new SoapHeader( 'http://soapinterop.org/echoheader/', 'user-token', $user_id ); 

$oSoapClient->__setSoapHeaders( $aHeaders );

$result = $oSoapClient->__doRequest( $sXml, $url, null, SOAP_1_1 );


And the server returns an error stating that the headers it requires were not found.
From the documentation for SOAP on php.net, I did not find anything new for myself.

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vamp, 2020-02-20
@lezhenkin

__setSoapHeaders sets the request's soap headers, not http. They are placed in the Header element. Your code example will look something like this:

<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="yourns"
    xmlns:ns2="http://soapinterop.org/echoheader/">
    <SOAP-ENV:Header>
        <ns2:token>token</ns2:token>
        <ns2:user-token>user_id</ns2:user-token>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <!-- тело запроса -->
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

To add exactly http headers, you need to create a stream context:
$aOptions['stream_context'] = stream_context_create([
    'http' => [
        'header' => "token: abc\r\nuser-token: 123"
    ]
]);

$oSoapClient = new SoapClient( $url, $aOptions );
$result = $oSoapClient->__doRequest( $sXml, $url, null, SOAP_1_1 );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question