gpt4 book ai didi

php - 如何通过 guzzle 运行 cURL

转载 作者:行者123 更新时间:2023-12-02 20:21:40 25 4
gpt4 key购买 nike

第一次使用cURL和guzzle。这可能是一个简单的问题,但希望有一个“helloworld”示例。

这是我当前拥有的 cURL:

curl --include --request POST \
--header "application/x-www-form-urlencoded" \
--header "X-Access-Token: ACCESS_TOKEN" \
--data-binary "grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY" \
'https://api.url.com/token'

这是guzzle代码:

$client = new Client(); //GuzzleHttp\Client
$result = $client->post('https://api.url.com/token', [
'form_params' => [
'sample-form-data' => 'value'
]
]);

我不确定如何使用 guzzle 运行 cURL 命令。生成的 guzzle 代码会是什么样子?

最佳答案

抱歉回复晚了,我看到你已经找到了a solution yourself 。虽然它有效,但这并不是像这样手动编码你的 body 有效负载的 Guzzle 方式/“最佳实践”。

Guzzle 为此提供了一种更简洁的方法,并在内部构建了主体有效负载:

$result = $client->post('https://api.url.com/token', [
'headers' => ['X-Access-Token' => 'ACCESS_TOKEN'],
'form_params' => [
'grant_type' => 'client_credentials',
'client_id' => 'PUBLIC_KEY',
'client_secret' => 'PRIVATE_KEY',
],
]);

?/& 的正确串联以及添加 application/x-www-form-urlencoded 是由 Guzzle 自动完成的。这是上面代码发送的请求:

POST /token HTTP/1.1
Content-Length: 76
User-Agent: GuzzleHttp/6.3.3 curl/7.57.0 PHP/7.2.2
Content-Type: application/x-www-form-urlencoded
Host: api.url.com
X-Access-Token: ACCESS_TOKEN

grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY

关于php - 如何通过 guzzle 运行 cURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51231370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com