Guzzle - Laravel.如何使用 x-www-form-url-encoded 发出请求 [英] Guzzle - Laravel. How to make request with x-www-form-url-encoded
问题描述
我需要集成一个 API,所以我编写了函数:
I need to integrate an API so I write function:
public function test() {
$client = new GuzzleHttpClient();
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 (GuzzleHttpExceptionClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
作为回复,我收到了消息:
as a responde I got message:
{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}
现在,当我尝试在 POSTMAN 应用程序中使用相同的数据运行相同的 url 时,我会得到正确的结果:
Now when I try to run the same url with same data in POSTMAN app then I get correct results:
我的代码有什么不好的地方?我发送了正确的 form_params
我也尝试将 form_params 更改为 json 但我又遇到了同样的错误......
What is bad in my code? I send correct form_params
also I try to change form_params to json but again I got the same error...
如何解决我的问题?
推荐答案
问题是在 Postman 中你是以表单形式发送数据,但在 Guzzle 中你是在 'json' 中传递数据
选项数组的键.
The problem is that in Postman you're sending the data as a form, but in Guzzle you're passing the data in the 'json'
key of the options array.
我敢打赌,如果你将 'json'
切换为 'form_params'
,你会得到你想要的结果.
I bet that if you would switch the 'json'
to 'form_params'
you would get the result you're looking for.
$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
Here's a link to the docs in question: http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields
另外,我注意到一个错字 - 你有 cliend_id
而不是 client_id
.
Also, I noticed a typo - you have cliend_id
instead of client_id
.
这篇关于Guzzle - Laravel.如何使用 x-www-form-url-encoded 发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!