gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:53:28 25 4
gpt4 key购买 nike

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

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

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

*编辑1:

回应pinkal vansia :我按照你的建议添加了标题:

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

并转储 header :

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

关于php - 如何向 GuzzleHTTP 请求对象添加身份验证以进行异步处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31052003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com