Laravel 与 Guzzle 中的多个 HTTP 请求存在问题



我正在使用Guzzle版本6.3.3。我想从外部 API 发出多个 HTTP 请求。下面显示的代码非常适合我。这只是一个请求。

public function getAllTeams()
{
$client = new Client();
$uri = 'https://api.football-data.org/v2/competitions/2003/teams';
$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$res = $client->get($uri, $header);
$data = json_decode($res->getBody()->getContents(), true);
return $data['teams'];
}

但是现在我想一次提出多个请求。在 Guzzle 的文档中,我找到了如何做到这一点,但它仍然无法正常工作。这是我尝试使用的代码。

$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$client = new Client(['debug' => true]);
$res = $client->send(array(
$client->get('https://api.football-data.org/v2/teams/666', $header),
$client->get('https://api.football-data.org/v2/teams/1920', $header),
$client->get('https://api.football-data.org/v2/teams/6806', $header)
));
$data = json_decode($res->getBody()->getContents(), true);
return $data;

我收到错误:

Argument 1 passed to GuzzleHttpClient::send() must implement interface PsrHttpMessageRequestInterface, array given called in TeamsController.

如果我在每个 URI 之后删除$header,则会收到此错误:

resulted in a '403 Forbidden' response: {"message": "The resource you are looking for is restricted. Please pass a valid API token and check your subscription fo (truncated...)

我尝试了几种方法使用我的 API 密钥设置X-Auth-Token。但是我仍然遇到错误,而且我不知道 Guzzle 设置它们的许多其他方法。

我希望有人能帮助我:)

Guzzle 6 对 Guzzle 3 使用了不同的方法,所以你应该使用类似的东西:

use function GuzzleHttpPromiseall;
$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$client = new Client(['debug' => true]);
$responses = all([
$client->getAsync('https://api.football-data.org/v2/teams/666', $header),
$client->getAsync('https://api.football-data.org/v2/teams/1920', $header),
$client->getAsync('https://api.football-data.org/v2/teams/6806', $header)
])->wait();
$data = [];
foreach ($responses as $i => $res) {
$data[$i] = json_decode($res->getBody()->getContents(), true);
}
return $data;

查看同一主题(#1、#2(的不同问题,以查看更多使用示例。

最新更新