如何为GuzzleHTTP请求对象添加身份验证以进行异步处理

时间:2015-06-25 13:38:03

标签: php authentication guzzle

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

(摘自Doc http://guzzle.readthedocs.org/en/latest/quickstart.html"并发请求")

这适用于对不需要身份验证且返回200 OK状态的URI的请求。

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

*编辑1:

回应pinkal 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

*最终编辑:

我终于让它运行了。事实证明,pinkal vansia已经非常接近了。

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

Authorization标头是要走的路,它需要是一个键=&gt;价值映射。

最后的事情看起来像这样:

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

1 个答案:

答案 0 :(得分:5)

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

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