【问题标题】:How to run cURL via guzzle如何通过 guzzle 运行 cURL
【发布时间】:2018-07-08 11:08:40
【问题描述】:

第一次使用 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 代码会是什么样子?

【问题讨论】:

  • 这应该已经发送了一个 POST 请求。假设您在 PHP 中启用了ext_curl,它甚至更喜欢使用 cURL。有什么问题?
  • 在您传递的选项数组中,您还可以放置 headers 键来传递 Auth/Token 标头。见docs.guzzlephp.org/en/stable/request-options.html
  • 如何使用 guzzle 编写上述 cURL 代码?生成的 php 代码会是什么样子?
  • 我不确定如何让问题更清楚。如果不清楚,我道歉。我基本上是在问如何在 php 中运行 cURL。我是 cURL 的新手。

标签: php curl guzzle


【解决方案1】:

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

Guzzle 为此提供了一种更简洁的方法,并在内部构建了 body-payload:

$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

【讨论】:

    【解决方案2】:

    以下是将 cURL 转换为 Guzzle 的答案。也许它会帮助像我一样需要“he​​lloworld”的未来人。这就是我通过 Guzzle 在 PHP 中运行 cURL 的方式:

    $client = new Client();
    $uri = 'https://api.url.com/token';
    $headers = [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'X-Access-Token' => $ACCESS_TOKEN
    ];
    $body = 'grant_type=client_credentials&client_id='.$PUBLIC_KEY.'&client_secret='.$PRIVATE_KEY;
    $result = $client->request('POST', $uri, [
        'headers' => $headers,
        'body' => $body
    ]);
    
    json_decode($result->getBody()->getContents(), true);
    

    不直观的两件事是您必须将 'application/x-www-form-urlencoded' 指定为 Content-Type。并将“数据二进制”作为“正文”。

    【讨论】:

      【解决方案3】:

      您可以通过调用“getBody”函数来获取/查看 Guzzle 调用的结果。在你的情况下, $result->getBody()

      【讨论】:

      • 也许我的问题不是很清楚?如果是这样我道歉。基本上我想弄清楚如何使用 php 运行 cURL 命令。这是我第一次使用 php 中的 cURL。
      猜你喜欢
      • 2016-05-26
      • 2020-01-18
      • 1970-01-01
      • 2018-02-11
      • 2023-02-12
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多