【问题标题】:Translate a PHP cURL to a bash cURL call将 PHP cURL 转换为 bash cURL 调用
【发布时间】:2016-05-29 22:54:03
【问题描述】:

我有这个进行 curl 调用的 PHP 代码:

  $postData['api_user'] = 'username';
   $postData['api_key'] = 'password!';

$ch = curl_init('https://api.example.com/send.json');
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

我知道为了在 bash 中使用 json 进行 curl 调用,我必须这样做:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource

但是我很困惑如何将我的所有 php 代码传输到 bash curl 调用,我的意思是例如什么相当于 curl_setopt(),并像我一样将凭据作为数组传递http_build_query()

【问题讨论】:

  • 为什么不把它保留为 PHP 并使用命令行 PHP 来运行它呢?
  • 因为我想知道如何使用这些选项运行 curl 调用

标签: php json bash curl scripting


【解决方案1】:

使用 cURL 将您的数据作为 JSON 发布。

curl -i \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-X POST --data '{"api_user": "username", "api_key":"password!"}' \
--insecure \
https://api.example.com/send.json

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 等于 -k, --insecure

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData))

等于-X POST --data ...

CURLOPT_RETURNTRANSFER...嗯,我不知道,)

【讨论】:

  • 在 POST --data 中,除了 api 用户和密钥之外,我还可以传递一系列选项吗?
  • 是的,--data 等于 POSTFIELDS。基本上是您在填写表格并按下提交后从浏览器发送的数据。您还可以查看 cURL 的手册页 - curl.haxx.se/docs/manpage.html - 只需搜索“--data”。
  • 谢谢,很有帮助
  • CURLOPT_RETURNTRANSFER 没有 CLI 等效项,因为它 prevents curl output 来自于标准输出,而不是 PHP 的 curl_exec 的返回值。在命令行中,所有输出都转到 stdout/stderr。
  • 这就是我根据您的代码得出的结论:fixee.org/paste/h01nphr 对我来说看起来不错。
【解决方案2】:

-d 是用于发送 POST 数据的 curl 标志,但您必须将其格式化为 JSON 字符串:

curl -H "Content-Type: application/json" -d '{ "api_user": "username", "api_key": "password" }' https://api.example.com/send.json

现在有了这些额外的选项(在curl man 页面中查找它们):

curl -X POST -k -H "Content-Type: application/json" -d '{ "api_user": "username", "api_key": "password" }' https://api.example.com/send.json

作为curl 的更友好的替代品,我建议查看httpie。以下是您使用httpie 拨打电话时的样子:

http --verify=no https://api.example.com/send.json api_user=username api_key=password

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 2017-08-03
    • 2019-06-04
    • 2017-12-03
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2017-01-01
    相关资源
    最近更新 更多