修改PHP/SOAP代码以在所有请求中添加HTTP标头
问题描述:
我继承了一些php SOAP代码,并且由于我们正在使用的服务发生更改,我需要修改以“在所有请求的HTTP标头中添加授权”。我不确定该做什么,甚至可能。相关代码的修改PHP/SOAP代码以在所有请求中添加HTTP标头
部分看起来是这样的:
function soap_connect() {
$soap_options = array(
'soap_version' => SOAP_1_2,
'encoding' => 'UTF-8',
'exceptions' => FALSE
);
try {
$this->soap_client = new SoapClient($this->configuration['wsdl'], $soap_options);
} catch (SoapFault $fault) {
return FALSE;
}
return TRUE;
}
我想,我的理解是,它应该只是输出以下(现在):
Content-Type: application/soap+xml;charset=UTF-8;action="http://ws.testserver.net/nsp/client/hsserve/listHardware"
Content-Length: 255
...
的documentatino说最终的HTTP请求应该如下所示:
Content-Type: application/soap+xml;charset=UTF-8;action="http://ws.testserver.net/nsp/client/hsserve/listHardware"
Authorization: WRAP access_token=Z-H7SnqL49eQ2Qp5pLH8k-RVxHfewgIIDt4VCeI2CNnrS4-gBMzPWbfZuMhgvISVV-uTSikS1SqO0n2PRkH3ysQ-uWbvU9podPAm6HiiIS5W2mtpXUfN9ErBmkjF6hDw
Content-Length: 255
答
要弄清楚在结构类型的服务器要求没有看到WSDL,但这里有几个例子:
简单的HTTP认证
$soap_options = array(
'soap_version' => SOAP_1_2,
'encoding' => 'UTF-8',
'exceptions' => FALSE,
'login' => 'username',
'password' => 'password'
);
try {
$this->soap_client = new SoapClient($this->configuration['wsdl'], $soap_options);
} catch (SoapFault $fault) {
return FALSE;
}
return TRUE;
对于其实现更先进的定制方法的服务器:
// Namespace for SOAP functions
$ns = 'Namespace/Goes/Here';
// Build an auth array
$auth = array();
$auth['AccountName'] = new SOAPVar($this->account['AccountName'], XSD_STRING, null, null, null, $ns);
$auth['ClientCode'] = new SOAPVar($this->account['ClientCode'], XSD_STRING, null, null, null, $ns);
$auth['Password'] = new SOAPVar($this->account['Password'], XSD_STRING, null, null, null, $ns);
// Create soap headers base off of the Namespace
$headerBody = new SOAPVar($auth, SOAP_ENC_OBJECT);
$header = new SOAPHeader($ns, 'SecuritySoapHeader', $headerBody);
$client->__setSOAPHeaders(array($header));
答
添加流上下文以向HTTP调用提供附加头。
function soap_connect() {
$context = array('http' =>
array(
'header' => 'Authorization: WRAP access_token=Z-H7SnqL49eQ2Qp5pLH8k-RVxHfewgIIDt4VCeI2CNnrS4-gBMzPWbfZuMhgvISVV-uTSikS1SqO0n2PRkH3ysQ-uWbvU9podPAm6HiiIS5W2mtpXUfN9ErBmkjF6hDw'
)
);
$soap_options = array(
'soap_version' => SOAP_1_2,
'encoding' => 'UTF-8',
'exceptions' => FALSE,
'stream_context' => stream_context_create($context)
);
try {
$this->soap_client = new SoapClient($this->configuration['wsdl'], $soap_options);
} catch (SoapFault $fault) {
return FALSE;
}
return TRUE;
}
完美。我甚至不知道你可以做到这一点。谢谢! – 2011-01-24 22:24:29