Laravel 5.1 Guzzle - 未定义的偏移量:0

时间:2018-04-28 13:36:56

标签: api laravel-5.1 guzzle guzzlehttp

我需要访问API,所以我使用guzzle6并编写一个函数:

public function test()
    {

$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);

try {
$res = $client->post('https://example.com/api/v2/oauth/token?grant_type=client_credentials', [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
    ],

    'auth' => [
        'Username' => 'user_5639',
        'Password' => 'pass_asdhbas67yausihd7qaw8'
]
            ]);

$res = json_decode($res->getBody()->getContents(), true);
}

catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $result =  json_decode($response->getBody()->getContents());

    return response()->json(['data' => $result]);
}

    }

但我收到了错误:

  

Client.php第346行中的ErrorException:未定义的偏移量:0

当我在POSTMAN尝试相同的请求时,一切都很好: enter image description here

如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

如果你看一下Guzzle Manual for the auth-option,你会发现它需要一个数字索引的数组,索引为0的用户名和索引1的密码。

所以这应该有效:

$res = $client->post('https://example.com/api/v2/oauth/token?grant_type=client_credentials', [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    'auth' => [
        'user_xxxx', 'pass_xxxxx'
    ]
]);