如何为 GuzzleHTTP Request Objects 添加身份验证以进行异步处理

How to add authentication to GuzzleHTTP Request Objects for asynchronous processing

我正在创建以下多个 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();

(摘自文档:"Concurrent requests" 下的 http://guzzle.readthedocs.org/en/latest/quickstart.html

这适用于不需要身份验证和 returns 200 OK 状态的 URI 请求。

如何向请求添加身份验证,以便池可以同时 运行 对受基本 HTTP 授权保护的 API 发出多个请求?

*编辑 1:

回应: 我按照您的建议添加了 header:

$headers = [
    'Authorization: Basic '. base64_encode($this->username.':'.$this->password),
];
$myRequest = new Request(
    'GET',
    $url,
    $headers
);`

并丢弃了 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

* 最终编辑:

我终于明白了运行宁。原来,已经很接近了。

确切的形式是最后一个问题。 评论让我走上正轨。

授权 header 是要走的路,它需要是键 => 值映射。

最后的样子是这样的:

$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;

您可以在请求中添加基本身份验证header,如下所示

$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
);