【发布时间】:2021-05-31 10:27:12
【问题描述】:
我只是想在新系统上实现 Guzzle,但收到以下错误消息:
PHP Fatal error: Uncaught InvalidArgumentException: Header value must be scalar or null but array provided. in /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/MessageTrait.php:191
Stack trace:
#0 [internal function]: GuzzleHttp\\Psr7\\Request->GuzzleHttp\\Psr7\\{closure}(Array)
#1 /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/MessageTrait.php(198): array_map(Object(Closure), Array)
#2 /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/MessageTrait.php(170): GuzzleHttp\\Psr7\\Request->trimHeaderValues(Array)
#3 /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/MessageTrait.php(148): GuzzleHttp\\Psr7\\Request->normalizeHeaderValue(Array)
#4 /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/Request.php(47): GuzzleHttp\\Psr7\\Request->setHeaders(Array)
#5 /var/www/html/lvmh/Library/Connectors/MySGS.php(114): GuzzleHttp\\Psr7\\Request->__construct('PUT', Object(GuzzleHttp\\Psr7\\Uri), Array)
#6 /var/www/html/lvmh/Library/Connectors/MySGS.php(139): JST\\Library\\Connectors\\MySGS->send('/integrationsap...', 'PUT', Array)
#7 /var/www/html/lvmh/public/secure/test_m in /var/www/html/lvmh/vendor/guzzlehttp/psr7/src/MessageTrait.php on line 191
我似乎无法找到问题所在或解决方法的单一来源。事实上,几乎没有人遇到过这个问题,因为我看到的错误消息的唯一引用来自代码本身。
这是我正在拨打的电话的示例:
/**
* Wraps and sends a message with the correct authentication fields in place.
* @param $uri string The path to the resource we're accessing.
* @param $method string HTTP method
* @param $body mixed Any valid JSON-convertible type.
* @return bool pass/fail
*/
private function send(string $uri, string $method, $body): bool
{
if ($this->getTokenValid()) {
$options = [
'headers' => [
'Authorization' => sprintf("Bearer %s", $this->token),
'Ocp-Apim-Subscription-Key' => SUBSCRIPTION_ID,
'Content-Type' => 'application/json'
],
'body' => $body
];
$request = new Request($method, $uri, $options);
try {
$req = $this->client->send($request);
return $req->getReasonPhrase();
} catch (ClientErrorResponseException $e) {
error_log($e->getMessage());
return false;
}
} else {
error_log('Not authenticated');
return false;
}
}
根据我自己的研究,我发现 MessageTrait 类在尝试创建标头时会生成此错误消息。但是发生的事情没有多大意义。如果我发送一个空数组,我会收到一条错误消息(类的第 167 行)“'Header value can not be an empty array.'” 但是,当我传递一个字符串数组时,它会给我上述错误消息。基于函数 normalizeHeaderValue(),即使我传入单个字符串,它也会将该值转换为数组,所以很明显,代码需要一个数组。
我很困惑。有人知道发生了什么吗?
【问题讨论】:
-
当您
var_dump($options)收到此错误的请求时,您会得到什么? -
你的版本?
-
检查
SUBSCRIPTION_ID的类型是否只在每种情况下都是字符串 -
@Cully 好主意,但看起来不错:一堆字符串。
-
@bhucho "guzzlehttp/guzzle": "^7.2"