我需要访问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
如何解决我的问题?
答案 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'
]
]);