我需要集成一个 API,所以我编写函数:
public function test() {
$client = new GuzzleHttp\Client();
try {
$res = $client->post('http://example.co.uk/auth/token', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'json' => [
'cliend_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
dd($res);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
作为回复者,我收到了消息:
{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}
现在,当我尝试在 POSTMAN 应用程序中使用相同的数据运行相同的 url 时,我得到了正确的结果:
我的代码有什么不好?我发送正确
form_params
我也尝试将 form_params 更改为 json 但我再次遇到相同的错误...如何解决我的问题?
最佳答案
问题在于,在 Postman 中,您将数据作为表单发送,但在 Guzzle 中,您将数据传递到 'json'
中。选项数组的键。
我敢打赌,如果你会切换 'json'
至 'form_params'
你会得到你正在寻找的结果。
$res = $client->post('http://example.co.uk/auth/token', [
'form_params' => [
'client_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
这是相关文档的链接:http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields
另外,我注意到一个错字 - 你有
cliend_id
而不是 client_id
.
关于laravel - Guzzle - Laravel。如何使用 x-www-form-url-encoded 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49681530/