Laravel with Guzzle中有多个HTTP请求的问题

问题描述 投票:0回答:1

我正在使用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 GuzzleHttp\Client::send() must implement interface Psr\Http\Message\RequestInterface, 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可以使用其他许多方式来设置它们。

我希望有人可以帮助我:)

laravel api httprequest guzzle guzzle6
1个回答
0
投票

Guzzle 6与Guzzle 3使用不同的方法,因此您应该使用类似的方法:

use function GuzzleHttp\Promise\all;

$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)的不同问题,以查看更多用法示例。

© www.soinside.com 2019 - 2024. All rights reserved.