我正在创建多个以下GuzzleHttp''Psr7''Requests:
use GuzzleHttp'Psr7'Request;
$myRequest = new Request(
'GET',
$someUri
);
并将它们保存在一个数组中:$guzzleRequests
然后我创建一个池来同时执行所有请求:
use GuzzleHttp'Pool;
$testPool = new Pool($testClient = new 'GuzzleHttp'Client(), $guzzlePromises,
[
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
var_dump($response);
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
var_dump($reason);
}
]);
// Initiate the transfers and create a promise
$promise = $testPool->promise();
// Force the pool of requests to complete.
$promise->wait();
(摘自文件:http://guzzle.readthedocs.org/en/latest/quickstart.html在"并发请求"下)
这适用于对不需要身份验证的URI的请求,并返回200 OK状态。
如何将身份验证添加到请求中,以便池可以同时针对受基本HTTP授权保护的API运行多个请求?
*编辑1:
针对粉红色vansia:我按照你的建议添加了标题:
$headers = [
'Authorization: Basic '. base64_encode($this->username.':'.$this->password),
];
$myRequest = new Request(
'GET',
$url,
$headers
);`
并转储标头:
array (size=2)
'Host' =>
array (size=1)
0 => string '<myHost>' (length=27)
0 =>
array (size=1)
0 => string 'Authorization: Basic <veryLongAuthenticationString>' (length=<stringLength>)`
响应仍然产生未经授权的:
private 'reasonPhrase' => string 'Unauthorized' (length=12)
private 'statusCode' => int 401
*最终编辑:
我终于让它运转起来了。事实证明,粉红色的vansia已经很接近了。
确切的形式是最后一个问题。迈克尔·唐宁的评论使我走上了正轨。
Authorization头是一种方法,它需要是一个键=>值映射。
最后一件事看起来是这样的:
$url = $myUrl.'?'.http_build_query($this->queryArray);
// ------------ Specify Authorization => key to make it work!!!
$headers = [
'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];
// -----------------------------------------------------------
$myRequest = new Request(
'GET',
$url,
$headers
);
return $myRequest;
您可以在请求中添加基本身份验证标头,如下所示
$headers = [
'Authorization: Basic '. base64_encode($this->username.':'.$this->password)
];
$myRequest = new Request(
'GET',
$url,
$headers
);
我希望这能有所帮助。
更新
正如@worps所指出的,header
需要是key => value
对。所以最终的解决方案如下,
$headers = [
'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];
$myRequest = new Request(
'GET',
$url,
$headers
);